code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.routing;
import com.google.common.collect.Iterators;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
/**
* A {@link RoutingNode} represents a cluster node associated with a single {@link DiscoveryNode} including all shards
* that are hosted on that nodes. Each {@link RoutingNode} has a unique node id that can be used to identify the node.
*/
public class RoutingNode implements Iterable<MutableShardRouting> {
private final String nodeId;
private final DiscoveryNode node;
private final List<MutableShardRouting> shards;
public RoutingNode(String nodeId, DiscoveryNode node) {
this(nodeId, node, new ArrayList<MutableShardRouting>());
}
public RoutingNode(String nodeId, DiscoveryNode node, List<MutableShardRouting> shards) {
this.nodeId = nodeId;
this.node = node;
this.shards = shards;
}
@Override
public Iterator<MutableShardRouting> iterator() {
return Iterators.unmodifiableIterator(shards.iterator());
}
Iterator<MutableShardRouting> mutableIterator() {
return shards.iterator();
}
/**
* Returns the nodes {@link DiscoveryNode}.
*
* @return discoveryNode of this node
*/
public DiscoveryNode node() {
return this.node;
}
/**
* Get the id of this node
* @return id of the node
*/
public String nodeId() {
return this.nodeId;
}
public int size() {
return shards.size();
}
/**
* Add a new shard to this node
* @param shard Shard to crate on this Node
*/
void add(MutableShardRouting shard) {
// TODO use Set with ShardIds for faster lookup.
for (MutableShardRouting shardRouting : shards) {
if (shardRouting.shardId().equals(shard.shardId())) {
throw new ElasticsearchIllegalStateException("Trying to add a shard [" + shard.shardId().index().name() + "][" + shard.shardId().id() + "] to a node [" + nodeId + "] where it already exists");
}
}
shards.add(shard);
}
/**
* Determine the number of shards with a specific state
* @param states set of states which should be counted
* @return number of shards
*/
public int numberOfShardsWithState(ShardRoutingState... states) {
int count = 0;
for (MutableShardRouting shardEntry : this) {
for (ShardRoutingState state : states) {
if (shardEntry.state() == state) {
count++;
}
}
}
return count;
}
/**
* Determine the shards with a specific state
* @param states set of states which should be listed
* @return List of shards
*/
public List<MutableShardRouting> shardsWithState(ShardRoutingState... states) {
List<MutableShardRouting> shards = newArrayList();
for (MutableShardRouting shardEntry : this) {
for (ShardRoutingState state : states) {
if (shardEntry.state() == state) {
shards.add(shardEntry);
}
}
}
return shards;
}
/**
* Determine the shards of an index with a specific state
* @param index id of the index
* @param states set of states which should be listed
* @return a list of shards
*/
public List<MutableShardRouting> shardsWithState(String index, ShardRoutingState... states) {
List<MutableShardRouting> shards = newArrayList();
for (MutableShardRouting shardEntry : this) {
if (!shardEntry.index().equals(index)) {
continue;
}
for (ShardRoutingState state : states) {
if (shardEntry.state() == state) {
shards.add(shardEntry);
}
}
}
return shards;
}
/**
* The number of shards on this node that will not be eventually relocated.
*/
public int numberOfOwningShards() {
int count = 0;
for (MutableShardRouting shardEntry : this) {
if (shardEntry.state() != ShardRoutingState.RELOCATING) {
count++;
}
}
return count;
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder();
sb.append("-----node_id[").append(nodeId).append("][" + (node == null ? "X" : "V") + "]\n");
for (MutableShardRouting entry : shards) {
sb.append("--------").append(entry.shortSummary()).append('\n');
}
return sb.toString();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("routingNode ([");
sb.append(node.getName());
sb.append("][");
sb.append(node.getId());
sb.append("][");
sb.append(node.getHostName());
sb.append("][");
sb.append(node.getHostAddress());
sb.append("], [");
sb.append(shards.size());
sb.append(" assigned shards])");
return sb.toString();
}
public MutableShardRouting get(int i) {
return shards.get(i) ;
}
public Collection<MutableShardRouting> copyShards() {
return new ArrayList<>(shards);
}
public boolean isEmpty() {
return shards.isEmpty();
}
}
| anti-social/elasticsearch | src/main/java/org/elasticsearch/cluster/routing/RoutingNode.java | Java | apache-2.0 | 6,412 |
/*
* Copyright (C) 2012-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package scala.compat.java8;
@FunctionalInterface
public interface JFunction2$mcZDJ$sp extends JFunction2 {
abstract boolean apply$mcZDJ$sp(double v1, long v2);
default Object apply(Object v1, Object v2) { return (Boolean) apply$mcZDJ$sp((Double) v1, (Long) v2); }
}
| yusuke2255/dotty | src/scala/compat/java8/JFunction2$mcZDJ$sp.java | Java | bsd-3-clause | 352 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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 program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.process.test;
import org.sonar.process.Monitored;
import org.sonar.process.ProcessEntryPoint;
import org.sonar.process.Lifecycle.State;
public class InfiniteTerminationProcess implements Monitored {
private State state = State.INIT;
private final Thread daemon = new Thread() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(100L);
}
} catch (InterruptedException e) {
// return
}
}
};
/**
* Blocks until started()
*/
@Override
public void start() {
state = State.STARTING;
daemon.start();
state = State.STARTED;
}
@Override
public boolean isReady() {
return state == State.STARTED;
}
@Override
public void awaitStop() {
try {
daemon.join();
} catch (InterruptedException e) {
// interrupted by call to terminate()
}
}
/**
* Blocks until stopped
*/
@Override
public void stop() {
state = State.STOPPING;
try {
daemon.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
state = State.STOPPED;
}
public static void main(String[] args) {
ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);
entryPoint.launch(new InfiniteTerminationProcess());
}
}
| vamsirajendra/sonarqube | server/sonar-process/src/test/java/org/sonar/process/test/InfiniteTerminationProcess.java | Java | lgpl-3.0 | 2,203 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.migration.migrators;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RealmRepresentation;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class MigrateTo1_2_0 implements Migration {
public static final ModelVersion VERSION = new ModelVersion("1.2.0");
@Override
public ModelVersion getVersion() {
return VERSION;
}
public void setupBrokerService(RealmModel realm) {
ClientModel client = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
if (client == null) {
client = KeycloakModelUtils.createManagementClient(realm, Constants.BROKER_SERVICE_CLIENT_ID);
client.setEnabled(true);
client.setName("${client_" + Constants.BROKER_SERVICE_CLIENT_ID + "}");
client.setFullScopeAllowed(false);
for (String role : Constants.BROKER_SERVICE_ROLES) {
RoleModel roleModel = client.getRole(role);
if (roleModel != null) continue;
roleModel = client.addRole(role);
roleModel.setDescription("${role_" + role.toLowerCase().replaceAll("_", "-") + "}");
}
}
}
private void setupClientNames(RealmModel realm) {
setupClientName(realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID));
setupClientName(realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID));
setupClientName(realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID));
}
private void setupClientName(ClientModel client) {
if (client != null && client.getName() == null) client.setName("${client_" + client.getClientId() + "}");
}
public void migrate(KeycloakSession session) {
session.realms().getRealmsStream().forEach(realm -> {
setupBrokerService(realm);
setupClientNames(realm);
});
}
@Override
public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) {
setupBrokerService(realm);
setupClientNames(realm);
}
}
| thomasdarimont/keycloak | server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_2_0.java | Java | apache-2.0 | 3,127 |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.impl.protocol.ssh;
import net.java.sip.communicator.service.protocol.*;
/**
* Very simple message implementation for the SSH protocol.
*
* @author Shobhit Jindal
* @author Lubomir Marinov
*/
public class MessageSSHImpl
extends AbstractMessage
{
/**
* The content type of the message.
*/
public static String contentType = "text/plain";
/**
* Creates a message instance according to the specified parameters.
*
* @param content the message body
* @param contentType message content type or null for text/plain
* @param contentEncoding message encoding or null for UTF8
* @param subject the subject of the message or null for no subject.
*/
public MessageSSHImpl(String content, String contentType,
String contentEncoding, String subject)
{
super(content, null, contentEncoding, subject);
MessageSSHImpl.contentType = contentType;
}
/**
* Returns the type of the content of this message.
*
* @return the type of the content of this message.
*/
@Override
public String getContentType()
{
return contentType;
}
}
| jibaro/jitsi | src/net/java/sip/communicator/impl/protocol/ssh/MessageSSHImpl.java | Java | apache-2.0 | 1,870 |
/*
* 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.cache;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import junit.framework.TestCase;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* Unit test for {@link AbstractCache}.
*
* @author Charles Fry
*/
public class AbstractCacheTest extends TestCase {
public void testGetAllPresent() {
final AtomicReference<Object> valueRef = new AtomicReference<Object>();
Cache<Object, Object> cache = new AbstractCache<Object, Object>() {
@Override
public Object getIfPresent(Object key) {
return valueRef.get();
}
};
assertNull(cache.getIfPresent(new Object()));
Object newValue = new Object();
valueRef.set(newValue);
assertSame(newValue, cache.getIfPresent(new Object()));
}
public void testInvalidateAll() {
final List<Object> invalidated = Lists.newArrayList();
Cache<Integer, Integer> cache = new AbstractCache<Integer, Integer>() {
@Override
public Integer getIfPresent(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void invalidate(Object key) {
invalidated.add(key);
}
};
List<Integer> toInvalidate = ImmutableList.of(1, 2, 3, 4);
cache.invalidateAll(toInvalidate);
assertEquals(toInvalidate, invalidated);
}
public void testEmptySimpleStats() {
StatsCounter counter = new SimpleStatsCounter();
CacheStats stats = counter.snapshot();
assertEquals(0, stats.requestCount());
assertEquals(0, stats.hitCount());
assertEquals(1.0, stats.hitRate());
assertEquals(0, stats.missCount());
assertEquals(0.0, stats.missRate());
assertEquals(0, stats.loadSuccessCount());
assertEquals(0, stats.loadExceptionCount());
assertEquals(0, stats.loadCount());
assertEquals(0, stats.totalLoadTime());
assertEquals(0.0, stats.averageLoadPenalty());
assertEquals(0, stats.evictionCount());
}
public void testSingleSimpleStats() {
StatsCounter counter = new SimpleStatsCounter();
for (int i = 0; i < 11; i++) {
counter.recordHits(1);
}
for (int i = 0; i < 13; i++) {
counter.recordLoadSuccess(i);
}
for (int i = 0; i < 17; i++) {
counter.recordLoadException(i);
}
for (int i = 0; i < 23; i++) {
counter.recordMisses(1);
}
for (int i = 0; i < 27; i++) {
counter.recordEviction();
}
CacheStats stats = counter.snapshot();
int requestCount = 11 + 23;
assertEquals(requestCount, stats.requestCount());
assertEquals(11, stats.hitCount());
assertEquals(11.0 / requestCount, stats.hitRate());
int missCount = 23;
assertEquals(missCount, stats.missCount());
assertEquals(((double) missCount) / requestCount, stats.missRate());
assertEquals(13, stats.loadSuccessCount());
assertEquals(17, stats.loadExceptionCount());
assertEquals(13 + 17, stats.loadCount());
assertEquals(214, stats.totalLoadTime());
assertEquals(214.0 / (13 + 17), stats.averageLoadPenalty());
assertEquals(27, stats.evictionCount());
}
public void testSimpleStatsIncrementBy() {
long totalLoadTime = 0;
SimpleStatsCounter counter1 = new SimpleStatsCounter();
for (int i = 0; i < 11; i++) {
counter1.recordHits(1);
}
for (int i = 0; i < 13; i++) {
counter1.recordLoadSuccess(i);
totalLoadTime += i;
}
for (int i = 0; i < 17; i++) {
counter1.recordLoadException(i);
totalLoadTime += i;
}
for (int i = 0; i < 19; i++) {
counter1.recordMisses(1);
}
for (int i = 0; i < 23; i++) {
counter1.recordEviction();
}
SimpleStatsCounter counter2 = new SimpleStatsCounter();
for (int i = 0; i < 27; i++) {
counter2.recordHits(1);
}
for (int i = 0; i < 31; i++) {
counter2.recordLoadSuccess(i);
totalLoadTime += i;
}
for (int i = 0; i < 37; i++) {
counter2.recordLoadException(i);
totalLoadTime += i;
}
for (int i = 0; i < 41; i++) {
counter2.recordMisses(1);
}
for (int i = 0; i < 43; i++) {
counter2.recordEviction();
}
counter1.incrementBy(counter2);
assertEquals(new CacheStats(38, 60, 44, 54, totalLoadTime, 66),
counter1.snapshot());
}
}
| gym0915/GoogleGuava | guava-tests/test/com/google/common/cache/AbstractCacheTest.java | Java | apache-2.0 | 5,060 |
/* 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.camunda.bpm.engine.test.jobexecutor;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.JobHandler;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.junit.Assert;
public class TweetHandler implements JobHandler {
List<String> messages = new ArrayList<String>();
public String getType() {
return "tweet";
}
public void execute(String configuration, ExecutionEntity execution, CommandContext commandContext) {
messages.add(configuration);
Assert.assertNotNull(commandContext);
}
public List<String> getMessages() {
return messages;
}
} | holisticon/camunda-bpm-platform | engine/src/test/java/org/camunda/bpm/engine/test/jobexecutor/TweetHandler.java | Java | apache-2.0 | 1,289 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution;
import java.lang.reflect.Method;
public abstract class TestDiscoveryListener {
public abstract String getFrameworkId();
public void testStarted(String className, String methodName) {
try {
final Object data = getData();
Method testStarted = data.getClass().getMethod("testStarted", new Class[] {String.class});
testStarted.invoke(data, new Object[] {className + "-" + methodName});
} catch (Throwable t) {
t.printStackTrace();
}
}
public void testFinished(String className, String methodName, boolean succeed) {
if (succeed) {
try {
final Object data = getData();
Method testEnded = data.getClass().getMethod("testEnded", new Class[] {String.class});
testEnded.invoke(data, new Object[] {getFrameworkId() + className + "-" + methodName});
} catch (Throwable t) {
t.printStackTrace();
}
}
}
protected Object getData() throws Exception {
return Class.forName("org.jetbrains.testme.instrumentation.ProjectData")
.getMethod("getProjectData", new Class[0])
.invoke(null, new Object[0]);
}
public void testRunStarted(String name) {}
public void testRunFinished(String name) {}
}
| samthor/intellij-community | java/java-runtime/src/com/intellij/execution/TestDiscoveryListener.java | Java | apache-2.0 | 1,844 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.client;
import javax.jms.Connection;
import javax.jms.JMSSecurityException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.management.ResourceNames;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.core.security.Role;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.jms.client.ActiveMQTemporaryTopic;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.artemis.tests.util.JMSTestBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.apache.activemq.artemis.api.core.management.ResourceNames.ADDRESS;
import static org.apache.activemq.artemis.api.core.management.ResourceNames.QUEUE;
public class AutoCreateJmsDestinationTest extends JMSTestBase {
public static final String QUEUE_NAME = "test";
@Test
public void testAutoCreateOnSendToQueue() throws Exception {
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = ActiveMQJMSClient.createQueue(QUEUE_NAME);
MessageProducer producer = session.createProducer(queue);
final int numMessages = 100;
for (int i = 0; i < numMessages; i++) {
TextMessage mess = session.createTextMessage("msg" + i);
producer.send(mess);
}
producer.close();
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
for (int i = 0; i < numMessages; i++) {
Message m = messageConsumer.receive(5000);
Assert.assertNotNull(m);
}
// make sure the JMX control was created for the address and queue
assertNotNull(server.getManagementService().getResource(ADDRESS + QUEUE_NAME));
assertNotNull(server.getManagementService().getResource(QUEUE + QUEUE_NAME));
connection.close();
}
@Test
public void testAutoCreateOnSendToQueueAnonymousProducer() throws Exception {
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = ActiveMQJMSClient.createQueue(QUEUE_NAME);
MessageProducer producer = session.createProducer(null);
final int numMessages = 100;
for (int i = 0; i < numMessages; i++) {
TextMessage mess = session.createTextMessage("msg" + i);
producer.send(queue, mess);
}
producer.close();
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
for (int i = 0; i < numMessages; i++) {
Message m = messageConsumer.receive(5000);
Assert.assertNotNull(m);
}
connection.close();
}
@Test
public void testAutoCreateOnSendToQueueSecurity() throws Exception {
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addUser("guest", "guest");
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().setDefaultUser("guest");
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addRole("guest", "rejectAll");
Role role = new Role("rejectAll", false, false, false, false, false, false, false, false, false, false);
Set<Role> roles = new HashSet<>();
roles.add(role);
server.getSecurityRepository().addMatch("#", roles);
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = ActiveMQJMSClient.createQueue(QUEUE_NAME);
try {
session.createProducer(queue);
Assert.fail("Sending a message here should throw a JMSSecurityException");
} catch (Exception e) {
Assert.assertTrue(e instanceof JMSSecurityException);
}
connection.close();
}
@Test
public void testAutoCreateOnSendToTopic() throws Exception {
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Topic topic = ActiveMQJMSClient.createTopic(QUEUE_NAME);
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("msg"));
connection.close();
assertNotNull(server.getManagementService().getResource(ResourceNames.ADDRESS + "test"));
}
@Test
public void testAutoCreateOnConsumeFromQueue() throws Exception {
Connection connection = null;
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = ActiveMQJMSClient.createQueue(QUEUE_NAME);
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
Message m = messageConsumer.receive(500);
Assert.assertNull(m);
Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(QUEUE_NAME)).getBindable();
Assert.assertEquals(0, q.getMessageCount());
Assert.assertEquals(0, q.getMessagesAdded());
connection.close();
}
@Test
public void testAutoCreateOnSubscribeToTopic() throws Exception {
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final String topicName = "test-" + UUID.randomUUID().toString();
javax.jms.Topic topic = ActiveMQJMSClient.createTopic(topicName);
MessageConsumer consumer = session.createConsumer(topic);
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("msg"));
connection.start();
assertNotNull(consumer.receive(500));
assertNotNull(server.getManagementService().getResource(ResourceNames.ADDRESS + topicName));
connection.close();
assertNull(server.getManagementService().getResource(ResourceNames.ADDRESS + topicName));
}
@Test
public void testAutoCreateOnDurableSubscribeToTopic() throws Exception {
Connection connection = cf.createConnection();
connection.setClientID("myClientID");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Topic topic = ActiveMQJMSClient.createTopic(QUEUE_NAME);
MessageConsumer consumer = session.createDurableConsumer(topic, "myDurableSub");
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("msg"));
connection.start();
assertNotNull(consumer.receive(500));
connection.close();
assertNotNull(server.getManagementService().getResource(ResourceNames.ADDRESS + "test"));
assertNotNull(server.locateQueue(SimpleString.toSimpleString("myClientID.myDurableSub")));
}
@Test
public void testTemporaryTopic() throws Exception {
Connection connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// javax.jms.Topic topic = ActiveMQJMSClient.createTopic(QUEUE_NAME);
ActiveMQTemporaryTopic topic = (ActiveMQTemporaryTopic) session.createTemporaryTopic();
MessageConsumer consumer = session.createConsumer(topic);
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("msg"));
connection.start();
assertNotNull(consumer.receive(500));
SimpleString topicAddress = topic.getSimpleAddress();
consumer.close();
assertNotNull(server.locateQueue(topicAddress));
IntegrationTestLogger.LOGGER.info("Topic name: " + topicAddress);
topic.delete();
connection.close();
// assertNotNull(server.getManagementService().getResource("jms.topic.test"));
assertNull(server.locateQueue(topicAddress));
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addUser("guest", "guest");
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().setDefaultUser("guest");
((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addRole("guest", "allowAll");
Role role = new Role("allowAll", true, true, true, true, true, true, true, true, true, true);
Set<Role> roles = new HashSet<>();
roles.add(role);
server.getSecurityRepository().addMatch("#", roles);
}
@Override
protected boolean useSecurity() {
return true;
}
}
| cshannon/activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/AutoCreateJmsDestinationTest.java | Java | apache-2.0 | 9,885 |
/*
* 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.spark.network.shuffle;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo;
import org.apache.spark.network.util.SystemPropertyConfigProvider;
import org.apache.spark.network.util.TransportConf;
import org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExternalShuffleBlockResolverSuite {
private static final String sortBlock0 = "Hello!";
private static final String sortBlock1 = "World!";
private static final String SORT_MANAGER = "org.apache.spark.shuffle.sort.SortShuffleManager";
private static TestShuffleDataContext dataContext;
private static final TransportConf conf =
new TransportConf("shuffle", new SystemPropertyConfigProvider());
@BeforeClass
public static void beforeAll() throws IOException {
dataContext = new TestShuffleDataContext(2, 5);
dataContext.create();
// Write some sort data.
dataContext.insertSortShuffleData(0, 0, new byte[][] {
sortBlock0.getBytes(StandardCharsets.UTF_8),
sortBlock1.getBytes(StandardCharsets.UTF_8)});
}
@AfterClass
public static void afterAll() {
dataContext.cleanup();
}
@Test
public void testBadRequests() throws IOException {
ExternalShuffleBlockResolver resolver = new ExternalShuffleBlockResolver(conf, null);
// Unregistered executor
try {
resolver.getBlockData("app0", "exec1", "shuffle_1_1_0");
fail("Should have failed");
} catch (RuntimeException e) {
assertTrue("Bad error message: " + e, e.getMessage().contains("not registered"));
}
// Invalid shuffle manager
try {
resolver.registerExecutor("app0", "exec2", dataContext.createExecutorInfo("foobar"));
resolver.getBlockData("app0", "exec2", "shuffle_1_1_0");
fail("Should have failed");
} catch (UnsupportedOperationException e) {
// pass
}
// Nonexistent shuffle block
resolver.registerExecutor("app0", "exec3",
dataContext.createExecutorInfo(SORT_MANAGER));
try {
resolver.getBlockData("app0", "exec3", "shuffle_1_1_0");
fail("Should have failed");
} catch (Exception e) {
// pass
}
}
@Test
public void testSortShuffleBlocks() throws IOException {
ExternalShuffleBlockResolver resolver = new ExternalShuffleBlockResolver(conf, null);
resolver.registerExecutor("app0", "exec0",
dataContext.createExecutorInfo(SORT_MANAGER));
InputStream block0Stream =
resolver.getBlockData("app0", "exec0", "shuffle_0_0_0").createInputStream();
String block0 = CharStreams.toString(
new InputStreamReader(block0Stream, StandardCharsets.UTF_8));
block0Stream.close();
assertEquals(sortBlock0, block0);
InputStream block1Stream =
resolver.getBlockData("app0", "exec0", "shuffle_0_0_1").createInputStream();
String block1 = CharStreams.toString(
new InputStreamReader(block1Stream, StandardCharsets.UTF_8));
block1Stream.close();
assertEquals(sortBlock1, block1);
}
@Test
public void jsonSerializationOfExecutorRegistration() throws IOException {
ObjectMapper mapper = new ObjectMapper();
AppExecId appId = new AppExecId("foo", "bar");
String appIdJson = mapper.writeValueAsString(appId);
AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);
assertEquals(parsedAppId, appId);
ExecutorShuffleInfo shuffleInfo =
new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, SORT_MANAGER);
String shuffleJson = mapper.writeValueAsString(shuffleInfo);
ExecutorShuffleInfo parsedShuffleInfo =
mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);
assertEquals(parsedShuffleInfo, shuffleInfo);
// Intentionally keep these hard-coded strings in here, to check backwards-compatability.
// its not legacy yet, but keeping this here in case anybody changes it
String legacyAppIdJson = "{\"appId\":\"foo\", \"execId\":\"bar\"}";
assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));
String legacyShuffleJson = "{\"localDirs\": [\"/bippy\", \"/flippy\"], " +
"\"subDirsPerLocalDir\": 7, \"shuffleManager\": " + "\"" + SORT_MANAGER + "\"}";
assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));
}
}
| Panos-Bletsos/spark-cost-model-optimizer | common/network-shuffle/src/test/java/org/apache/spark/network/shuffle/ExternalShuffleBlockResolverSuite.java | Java | apache-2.0 | 5,447 |
/*
Copyright 2006 Jerry Huxtable
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.
*/
/*
* This file was semi-automatically converted from the public-domain USGS PROJ source.
*/
package com.jhlabs.map.proj;
public class Murdoch2Projection extends SimpleConicProjection {
public Murdoch2Projection() {
super( SimpleConicProjection.MURD2 );
}
public String toString() {
return "Murdoch II";
}
}
| pomadchin/owm-jmapprojlib | src/main/java/com/jhlabs/map/proj/Murdoch2Projection.java | Java | apache-2.0 | 882 |
/*
* Copyright 2018 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.drools.verifier.core.checks;
import java.util.Arrays;
import java.util.HashSet;
import org.drools.verifier.api.reporting.CheckType;
import org.drools.verifier.api.reporting.Issue;
import org.drools.verifier.api.reporting.Severity;
import org.drools.verifier.core.cache.inspectors.RuleInspector;
import org.drools.verifier.core.checks.base.SingleCheck;
import org.drools.verifier.core.configuration.AnalyzerConfiguration;
public class DetectMissingConditionCheck
extends SingleCheck {
public DetectMissingConditionCheck(final RuleInspector ruleInspector,
final AnalyzerConfiguration configuration) {
super(ruleInspector,
configuration,
CheckType.MISSING_RESTRICTION);
}
@Override
public boolean check() {
return hasIssues = ruleInspector.atLeastOneActionHasAValue() && !ruleInspector.atLeastOneConditionHasAValue();
}
@Override
protected Severity getDefaultSeverity() {
return Severity.NOTE;
}
@Override
protected Issue makeIssue(final Severity severity,
final CheckType checkType) {
return new Issue(severity,
checkType,
new HashSet<>(Arrays.asList(ruleInspector.getRowIndex() + 1))
);
}
}
| droolsjbpm/drools | drools-verifier/drools-verifier-core/src/main/java/org/drools/verifier/core/checks/DetectMissingConditionCheck.java | Java | apache-2.0 | 1,969 |
/*
Copyright (c) Microsoft Open Technologies, Inc.
All Rights Reserved
Apache 2.0 License
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.
See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.UserAuthenticationCallback;
import com.microsoft.windowsazure.mobileservices.authentication.MobileServiceAuthenticationProvider;
import com.microsoft.windowsazure.mobileservices.authentication.MobileServiceUser;
import com.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable;
import com.microsoft.windowsazure.mobileservices.table.TableDeleteCallback;
import com.microsoft.windowsazure.mobileservices.table.TableJsonOperationCallback;
import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.LogServiceFilter;
import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestCase;
import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestExecutionCallback;
import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestGroup;
import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestResult;
import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestStatus;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponse;
public class LoginTests extends TestGroup {
protected static final String APPLICATION_PERMISSION_TABLE_NAME = "application";
protected static final String USER_PERMISSION_TABLE_NAME = "authenticated";
protected static final String ADMIN_PERMISSION_TABLE_NAME = "admin";
private static JsonObject lastUserIdentityObject;
public LoginTests() {
super("Login tests");
this.addTest(createLogoutTest("1"));
this.addTest(createCRUDTest(APPLICATION_PERMISSION_TABLE_NAME, null, TablePermission.Application, false));
this.addTest(createCRUDTest(USER_PERMISSION_TABLE_NAME, null, TablePermission.User, false));
this.addTest(createCRUDTest(ADMIN_PERMISSION_TABLE_NAME, null, TablePermission.Admin, false));
int indexOfStartAuthenticationTests = this.getTestCases().size();
ArrayList<MobileServiceAuthenticationProvider> providersWithRecycledTokenSupport = new ArrayList<MobileServiceAuthenticationProvider>();
providersWithRecycledTokenSupport.add(MobileServiceAuthenticationProvider.Facebook);
// Known bug - Drop login via Google token until Google client flow is
// reintroduced
// providersWithRecycledTokenSupport.add(MobileServiceAuthenticationProvider.Google);
for (MobileServiceAuthenticationProvider provider : MobileServiceAuthenticationProvider.values()) {
this.addTest(createLogoutTest("2"));
this.addTest(createLoginTest(provider));
this.addTest(createCRUDTest(APPLICATION_PERMISSION_TABLE_NAME, provider, TablePermission.Application, true));
this.addTest(createCRUDTest(USER_PERMISSION_TABLE_NAME, provider, TablePermission.User, true));
this.addTest(createCRUDTest(ADMIN_PERMISSION_TABLE_NAME, provider, TablePermission.Admin, true));
if (providersWithRecycledTokenSupport.contains(provider)) {
this.addTest(createLogoutTest("3"));
this.addTest(createClientSideLoginTest(provider));
this.addTest(createCRUDTest(USER_PERMISSION_TABLE_NAME, provider, TablePermission.User, true));
}
}
// this.addTest(createLogoutTest());
// this.addTest(createLoginWithGoogleAccountTest(true, null));
//
// this.addTest(createLogoutTest());
// this.addTest(createLoginWithGoogleAccountTest(true,
// MobileServiceClient.GOOGLE_USER_INFO_SCOPE +
// " https://www.googleapis.com/auth/userinfo.email"));
//
// this.addTest(createLogoutTest());
// this.addTest(createLoginWithGoogleAccountTest(false, null));
// With Callback
this.addTest(createLogoutWithCallbackTest());
this.addTest(createLoginWithCallbackTest(MobileServiceAuthenticationProvider.Google));
this.addTest(createCRUDWithCallbackTest(USER_PERMISSION_TABLE_NAME, MobileServiceAuthenticationProvider.Google, TablePermission.User, true));
this.addTest(createLogoutWithCallbackTest());
this.addTest(createLoginWithCallbackTest(MobileServiceAuthenticationProvider.Facebook));
this.addTest(createCRUDWithCallbackTest(USER_PERMISSION_TABLE_NAME, MobileServiceAuthenticationProvider.Facebook, TablePermission.User, true));
this.addTest(createLogoutWithCallbackTest());
this.addTest(createClientSideLoginWithCallbackTest(providersWithRecycledTokenSupport.get(0)));
this.addTest(createLogoutWithCallbackTest());
// this.addTest(createLoginWithGoogleAccountWithCallbackTest(false,
// null));
List<TestCase> testCases = this.getTestCases();
for (int i = indexOfStartAuthenticationTests; i < testCases.size(); i++) {
testCases.get(i).setCanRunUnattended(false);
}
}
private TestCase createClientSideLoginTest(final MobileServiceAuthenticationProvider provider) {
TestCase test = new TestCase("Login via token for " + provider.toString()) {
@Override
protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {
final TestCase testCase = this;
long seed = new Date().getTime();
final Random rndGen = new Random(seed);
if (lastUserIdentityObject == null) {
log("Last identity is null. Cannot run this test.");
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
testResult.setStatus(TestStatus.Failed);
callback.onTestComplete(testCase, testResult);
return;
}
JsonObject lastIdentity = lastUserIdentityObject;
lastUserIdentityObject = null;
JsonObject providerIdentity = new JsonParser().parse(lastIdentity.get("Identities").getAsString()).getAsJsonObject()
.getAsJsonObject(provider.toString().toLowerCase(Locale.US));
if (providerIdentity == null) {
log("Cannot find identity for specified provider. Cannot run this test.");
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
testResult.setStatus(TestStatus.Failed);
callback.onTestComplete(testCase, testResult);
return;
}
JsonObject token = new JsonObject();
token.addProperty("access_token", providerIdentity.get("accessToken").getAsString());
boolean useEnumOverload = rndGen.nextBoolean();
if (useEnumOverload) {
log("Calling the overload MobileServiceClient.login(MobileServiceAuthenticationProvider, JsonObject, UserAuthenticationCallback)");
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
try {
MobileServiceUser user = client.login(provider, token).get();
log("Logged in as " + user.getUserId());
testResult.setStatus(TestStatus.Passed);
} catch (Exception exception) {
log("Exception during login: " + exception.toString());
testResult.setStatus(TestStatus.Failed);
}
callback.onTestComplete(testCase, testResult);
} else {
log("Calling the overload MobileServiceClient.login(String, JsonObject, UserAuthenticationCallback)");
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
try {
MobileServiceUser user = client.login(provider.toString(), token).get();
log("Logged in as " + user.getUserId());
testResult.setStatus(TestStatus.Passed);
} catch (Exception exception) {
log("Exception during login: " + exception.toString());
testResult.setStatus(TestStatus.Failed);
}
callback.onTestComplete(testCase, testResult);
}
}
};
return test;
}
public static TestCase createLoginTest(final MobileServiceAuthenticationProvider provider) {
TestCase test = new TestCase("Login with " + provider.toString()) {
@Override
protected void executeTest(final MobileServiceClient client, final TestExecutionCallback callback) {
try {
final TestCase testCase = this;
long seed = new Date().getTime();
final Random rndGen = new Random(seed);
boolean useEnumOverload = rndGen.nextBoolean();
if (useEnumOverload) {
log("Calling the overload MobileServiceClient.login(MobileServiceAuthenticationProvider, UserAuthenticationCallback)");
TestResult result = new TestResult();
String userName;
try {
MobileServiceUser user = client.login(provider).get();
userName = user.getUserId();
} catch (Exception exception) {
userName = "NULL";
log("Error during login, user == null");
log("Exception: " + exception.toString());
}
log("Logged in as " + userName);
MobileServiceUser currentUser = client.getCurrentUser();
if (currentUser == null) {
result.setStatus(TestStatus.Failed);
} else {
result.setStatus(TestStatus.Passed);
}
result.setTestCase(testCase);
callback.onTestComplete(testCase, result);
} else {
log("Calling the overload MobileServiceClient.login(String, UserAuthenticationCallback)");
TestResult result = new TestResult();
String userName;
try {
MobileServiceUser user = client.login(provider.toString()).get();
userName = user.getUserId();
} catch (Exception exception) {
userName = "NULL";
log("Error during login, user == null");
log("Exception: " + exception.toString());
}
log("Logged in as " + userName);
MobileServiceUser currentUser = client.getCurrentUser();
if (currentUser == null) {
result.setStatus(TestStatus.Failed);
} else {
result.setStatus(TestStatus.Passed);
}
result.setTestCase(testCase);
callback.onTestComplete(testCase, result);
}
} catch (Exception e) {
callback.onTestComplete(this, createResultFromException(e));
return;
}
}
};
return test;
}
enum TablePermission {
Public, Application, User, Admin
}
public static TestCase createLogoutTest(String extraName) {
TestCase test = new TestCase() {
@Override
protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
client.logout();
log("Logged out");
TestResult result = new TestResult();
result.setTestCase(this);
result.setStatus(client.getCurrentUser() == null ? TestStatus.Passed : TestStatus.Failed);
callback.onTestComplete(this, result);
}
};
test.setName("Logout " + extraName);
return test;
}
private TestCase createCRUDTest(final String tableName, final MobileServiceAuthenticationProvider provider, final TablePermission tableType,
final boolean userIsAuthenticated) {
final TestCase test = new TestCase() {
@Override
protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {
final TestResult result = new TestResult();
result.setStatus(TestStatus.Passed);
result.setTestCase(this);
final TestCase testCase = this;
MobileServiceClient logClient = client.withFilter(new LogServiceFilter());
final MobileServiceJsonTable table = logClient.getTable(tableName);
final boolean crudShouldWork = tableType == TablePermission.Public || tableType == TablePermission.Application
|| (tableType == TablePermission.User && userIsAuthenticated);
final JsonObject item = new JsonObject();
item.addProperty("name", "John Doe");
log("insert item");
int id = 1;
try {
JsonObject jsonEntityInsert = table.insert(item).get();
id = jsonEntityInsert.get("id").getAsInt();
item.addProperty("id", id);
} catch (Exception exception) {
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
}
item.addProperty("name", "Jane Doe");
log("update item");
try {
table.update(item).get();
} catch (Exception exception) {
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
}
log("lookup item");
try {
JsonElement jsonEntityLookUp = table.lookUp(item.get("id").getAsInt()).get();
if (userIsAuthenticated && tableType == TablePermission.User) {
lastUserIdentityObject = jsonEntityLookUp.getAsJsonObject();
}
log("delete item");
} catch (Exception exception) {
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
}
try {
table.delete(item.get("id").getAsInt()).get();
} catch (Exception exception) {
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
}
callback.onTestComplete(testCase, result);
return;
}
private boolean validateExecution(boolean crudShouldWork, Exception exception, TestResult result) {
if (crudShouldWork && exception != null || !crudShouldWork && exception == null) {
createResultFromException(result, exception);
result.setStatus(TestStatus.Failed);
return false;
} else {
return true;
}
}
};
String testKind;
if (userIsAuthenticated) {
testKind = "auth by " + provider.toString();
} else {
testKind = "unauthenticated";
}
String testName = String.format(Locale.getDefault(), "CRUD, %s, table with %s permissions", testKind, tableType.toString());
test.setName(testName);
return test;
}
@SuppressWarnings("deprecation")
private TestCase createClientSideLoginWithCallbackTest(final MobileServiceAuthenticationProvider provider) {
TestCase test = new TestCase("With Callback - Login via token for " + provider.toString()) {
@Override
protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {
final TestCase testCase = this;
long seed = new Date().getTime();
final Random rndGen = new Random(seed);
if (lastUserIdentityObject == null) {
log("Last identity is null. Cannot run this test.");
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
testResult.setStatus(TestStatus.Failed);
callback.onTestComplete(testCase, testResult);
return;
}
JsonObject lastIdentity = lastUserIdentityObject;
lastUserIdentityObject = null;
JsonObject providerIdentity = lastIdentity.getAsJsonObject(provider.toString().toLowerCase(Locale.US));
if (providerIdentity == null) {
log("Cannot find identity for specified provider. Cannot run this test.");
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
testResult.setStatus(TestStatus.Failed);
callback.onTestComplete(testCase, testResult);
return;
}
JsonObject token = new JsonObject();
token.addProperty("access_token", providerIdentity.get("accessToken").getAsString());
UserAuthenticationCallback authCallback = new UserAuthenticationCallback() {
@Override
public void onCompleted(MobileServiceUser user, Exception exception, ServiceFilterResponse response) {
TestResult testResult = new TestResult();
testResult.setTestCase(testCase);
if (exception != null) {
log("Exception during login: " + exception.toString());
testResult.setStatus(TestStatus.Failed);
} else {
log("Logged in as " + user.getUserId());
testResult.setStatus(TestStatus.Passed);
}
callback.onTestComplete(testCase, testResult);
}
};
boolean useEnumOverload = rndGen.nextBoolean();
if (useEnumOverload) {
log("Calling the overload MobileServiceClient.login(MobileServiceAuthenticationProvider, JsonObject, UserAuthenticationCallback)");
client.login(provider, token, authCallback);
} else {
log("Calling the overload MobileServiceClient.login(String, JsonObject, UserAuthenticationCallback)");
client.login(provider.toString(), token, authCallback);
}
}
};
return test;
}
@SuppressWarnings("deprecation")
public static TestCase createLoginWithCallbackTest(final MobileServiceAuthenticationProvider provider) {
TestCase test = new TestCase("With Callback - Login with " + provider.toString()) {
@Override
protected void executeTest(final MobileServiceClient client, final TestExecutionCallback callback) {
final TestCase testCase = this;
long seed = new Date().getTime();
final Random rndGen = new Random(seed);
UserAuthenticationCallback authCallback = new UserAuthenticationCallback() {
@Override
public void onCompleted(MobileServiceUser user, Exception exception, ServiceFilterResponse response) {
TestResult result = new TestResult();
String userName;
if (user == null) {
log("Error during login, user == null");
if (exception != null) {
log("Exception: " + exception.toString());
}
userName = "NULL";
} else {
userName = user.getUserId();
}
log("Logged in as " + userName);
result.setStatus(client.getCurrentUser() != null ? TestStatus.Passed : TestStatus.Failed);
result.setTestCase(testCase);
callback.onTestComplete(testCase, result);
}
};
boolean useEnumOverload = rndGen.nextBoolean();
if (useEnumOverload) {
log("Calling the overload MobileServiceClient.login(MobileServiceAuthenticationProvider, UserAuthenticationCallback)");
client.login(provider, authCallback);
} else {
log("Calling the overload MobileServiceClient.login(String, UserAuthenticationCallback)");
client.login(provider.toString(), authCallback);
}
}
};
return test;
}
public static TestCase createLogoutWithCallbackTest() {
TestCase test = new TestCase() {
@Override
protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
client.logout();
log("Logged out");
TestResult result = new TestResult();
result.setTestCase(this);
result.setStatus(client.getCurrentUser() == null ? TestStatus.Passed : TestStatus.Failed);
callback.onTestComplete(this, result);
}
};
test.setName("With Callback - Logout");
return test;
}
@SuppressWarnings("deprecation")
private TestCase createCRUDWithCallbackTest(final String tableName, final MobileServiceAuthenticationProvider provider, final TablePermission tableType,
final boolean userIsAuthenticated) {
final TestCase test = new TestCase() {
@Override
protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) {
final TestResult result = new TestResult();
result.setStatus(TestStatus.Passed);
result.setTestCase(this);
final TestCase testCase = this;
MobileServiceClient logClient = client.withFilter(new LogServiceFilter());
final MobileServiceJsonTable table = logClient.getTable(tableName);
final boolean crudShouldWork = tableType == TablePermission.Public || tableType == TablePermission.Application
|| (tableType == TablePermission.User && userIsAuthenticated);
final JsonObject item = new JsonObject();
item.addProperty("name", "John Doe");
log("insert item");
table.insert(item, new TableJsonOperationCallback() {
@Override
public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) {
int id = 1;
if (exception == null) {
id = jsonEntity.get("id").getAsInt();
}
item.addProperty("id", id);
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
item.addProperty("name", "Jane Doe");
log("update item");
table.update(item, new TableJsonOperationCallback() {
@Override
public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) {
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
log("lookup item");
table.lookUp(item.get("id").getAsInt(), new TableJsonOperationCallback() {
@Override
public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) {
if (!validateExecution(crudShouldWork, exception, result)) {
callback.onTestComplete(testCase, result);
return;
}
if (userIsAuthenticated && tableType == TablePermission.User) {
lastUserIdentityObject = new JsonParser().parse(jsonEntity.get("Identities").getAsString()).getAsJsonObject();
}
log("delete item");
table.delete(item.get("id").getAsInt(), new TableDeleteCallback() {
@Override
public void onCompleted(Exception exception, ServiceFilterResponse response) {
validateExecution(crudShouldWork, exception, result);
callback.onTestComplete(testCase, result);
return;
}
});
}
});
}
});
}
});
}
private boolean validateExecution(boolean crudShouldWork, Exception exception, TestResult result) {
if (crudShouldWork && exception != null || !crudShouldWork && exception == null) {
createResultFromException(result, exception);
result.setStatus(TestStatus.Failed);
return false;
} else {
return true;
}
}
};
String testKind;
if (userIsAuthenticated) {
testKind = "auth by " + provider.toString();
} else {
testKind = "unauthenticated";
}
String testName = String.format(Locale.getDefault(), "CRUD With Callback, %s, table with %s permissions", testKind, tableType.toString());
test.setName(testName);
return test;
}
}
| brettsam/azure-mobile-services-test | sdk/Android/ZumoE2ETestApp/src/com/microsoft/windowsazure/mobileservices/zumoe2etestapp/tests/LoginTests.java | Java | apache-2.0 | 22,647 |
/*
Copyright (c) Microsoft Open Technologies, Inc.
All Rights Reserved
Apache 2.0 License
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.
See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests;
import com.google.common.util.concurrent.ListenableFuture;
import com.microsoft.windowsazure.mobileservices.http.NextServiceFilterCallback;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilter;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterRequest;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponse;
public class RemoveAuthenticationServiceFilter implements ServiceFilter {
@Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
NextServiceFilterCallback nextServiceFilterCallback) {
request.removeHeader("X-ZUMO-AUTH");
request.removeHeader("X-ZUMO-APPLICATION");
return nextServiceFilterCallback.onNext(request);
}
}
| brettsam/azure-mobile-services-test | sdk/Android/ZumoE2ETestApp/src/com/microsoft/windowsazure/mobileservices/zumoe2etestapp/tests/RemoveAuthenticationServiceFilter.java | Java | apache-2.0 | 1,589 |
/*
* Copyright 2010-2015 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.logs.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.logs.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* Describe Destinations Request Marshaller
*/
public class DescribeDestinationsRequestMarshaller implements Marshaller<Request<DescribeDestinationsRequest>, DescribeDestinationsRequest> {
public Request<DescribeDestinationsRequest> marshall(DescribeDestinationsRequest describeDestinationsRequest) {
if (describeDestinationsRequest == null) {
throw new AmazonClientException("Invalid argument passed to marshall(...)");
}
Request<DescribeDestinationsRequest> request = new DefaultRequest<DescribeDestinationsRequest>(describeDestinationsRequest, "AWSLogs");
String target = "Logs_20140328.DescribeDestinations";
request.addHeader("X-Amz-Target", target);
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
StringWriter stringWriter = new StringWriter();
JSONWriter jsonWriter = new JSONWriter(stringWriter);
jsonWriter.object();
if (describeDestinationsRequest.getDestinationNamePrefix() != null) {
jsonWriter.key("DestinationNamePrefix").value(describeDestinationsRequest.getDestinationNamePrefix());
}
if (describeDestinationsRequest.getNextToken() != null) {
jsonWriter.key("nextToken").value(describeDestinationsRequest.getNextToken());
}
if (describeDestinationsRequest.getLimit() != null) {
jsonWriter.key("limit").value(describeDestinationsRequest.getLimit());
}
jsonWriter.endObject();
String snippet = stringWriter.toString();
byte[] content = snippet.getBytes(UTF8);
request.setContent(new StringInputStream(snippet));
request.addHeader("Content-Length", Integer.toString(content.length));
request.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch(Throwable t) {
throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| mahaliachante/aws-sdk-java | aws-java-sdk-logs/src/main/java/com/amazonaws/services/logs/model/transform/DescribeDestinationsRequestMarshaller.java | Java | apache-2.0 | 3,541 |
/*
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package java.lang;
import com.facebook.infer.models.InferBuiltins;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
public final class System {
private System() {
}
public final static InputStream in;
static {
byte[] arr = {0};
in = new ByteArrayInputStream(arr);
}
public final static PrintStream out = new PrintStream(
new ByteArrayOutputStream());
public final static PrintStream err = new PrintStream(
new ByteArrayOutputStream());
public static void exit(int status) {
InferBuiltins._exit();
}
}
| wangwei1237/infer | infer/models/java/src/java/lang/System.java | Java | bsd-3-clause | 981 |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.predicate;
import org.fenixedu.academic.domain.ExecutionCourse;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.space.LessonInstanceSpaceOccupation;
import org.fenixedu.academic.domain.space.LessonSpaceOccupation;
import org.fenixedu.academic.domain.space.SpaceOccupation;
import org.fenixedu.academic.domain.space.WrittenEvaluationSpaceOccupation;
public class SpacePredicates {
private static final AccessControlPredicate<SpaceOccupation> checkPermissionsToManageOccupationsWithoutCheckSpaceManager =
new AccessControlPredicate<SpaceOccupation>() {
@Override
public boolean evaluate(SpaceOccupation spaceOccupation) {
spaceOccupation.checkPermissionsToManageSpaceOccupationsWithoutCheckSpaceManager();
return true;
}
};
public static final AccessControlPredicate<WrittenEvaluationSpaceOccupation> checkPermissionsToManageWrittenEvaluationSpaceOccupations =
new AccessControlPredicate<WrittenEvaluationSpaceOccupation>() {
@Override
public boolean evaluate(WrittenEvaluationSpaceOccupation spaceOccupation) {
// ResourceAllocationRole.checkIfPersonHasPermissionToManageSchedulesAllocation(AccessControl.getPerson());
return checkPermissionsToManageOccupationsWithoutCheckSpaceManager.evaluate(spaceOccupation);
}
};
//
public static final AccessControlPredicate<LessonSpaceOccupation> checkPermissionsToManageLessonSpaceOccupations =
new AccessControlPredicate<LessonSpaceOccupation>() {
@Override
public boolean evaluate(LessonSpaceOccupation spaceOccupation) {
// ResourceAllocationRole.checkIfPersonHasPermissionToManageSchedulesAllocation(AccessControl.getPerson());
return checkPermissionsToManageOccupationsWithoutCheckSpaceManager.evaluate(spaceOccupation);
}
};
//
public static final AccessControlPredicate<LessonSpaceOccupation> checkPermissionsToDeleteLessonSpaceOccupations =
new AccessControlPredicate<LessonSpaceOccupation>() {
@Override
public boolean evaluate(LessonSpaceOccupation spaceOccupation) {
Person loggedPerson = AccessControl.getPerson();
ExecutionCourse executionCourse = spaceOccupation.getLesson().getExecutionCourse();
if (loggedPerson.hasProfessorshipForExecutionCourse(executionCourse)) {
return true;
}
return checkPermissionsToManageLessonSpaceOccupations.evaluate(spaceOccupation);
}
};
//
public static final AccessControlPredicate<LessonInstanceSpaceOccupation> checkPermissionsToManageLessonInstanceSpaceOccupations =
new AccessControlPredicate<LessonInstanceSpaceOccupation>() {
@Override
public boolean evaluate(LessonInstanceSpaceOccupation lessonInstanceSpaceOccupation) {
// ResourceAllocationRole.checkIfPersonHasPermissionToManageSchedulesAllocation(AccessControl.getPerson());
return true;
}
};
//
public static final AccessControlPredicate<LessonInstanceSpaceOccupation> checkPermissionsToManageLessonInstanceSpaceOccupationsWithTeacherCheck =
new AccessControlPredicate<LessonInstanceSpaceOccupation>() {
@Override
public boolean evaluate(LessonInstanceSpaceOccupation lessonInstanceSpaceOccupation) {
Person loggedPerson = AccessControl.getPerson();
if (loggedPerson.getProfessorshipsSet().size() > 0) {
return true;
}
// ResourceAllocationRole.checkIfPersonHasPermissionToManageSchedulesAllocation(loggedPerson);
return true;
}
};
}
| JNPA/fenixedu-academic | src/main/java/org/fenixedu/academic/predicate/SpacePredicates.java | Java | lgpl-3.0 | 4,905 |
/**
* 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.ahc.springboot;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.component.ahc.AhcComponent;
import org.apache.camel.util.IntrospectionSupport;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Configuration
@ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@Conditional(AhcComponentAutoConfiguration.Condition.class)
@AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@EnableConfigurationProperties(AhcComponentConfiguration.class)
public class AhcComponentAutoConfiguration {
@Lazy
@Bean(name = "ahc-component")
@ConditionalOnClass(CamelContext.class)
@ConditionalOnMissingBean(AhcComponent.class)
public AhcComponent configureAhcComponent(CamelContext camelContext,
AhcComponentConfiguration configuration) throws Exception {
AhcComponent component = new AhcComponent();
component.setCamelContext(camelContext);
Map<String, Object> parameters = new HashMap<>();
IntrospectionSupport.getProperties(configuration, parameters, null,
false);
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
Object value = entry.getValue();
Class<?> paramClass = value.getClass();
if (paramClass.getName().endsWith("NestedConfiguration")) {
Class nestedClass = null;
try {
nestedClass = (Class) paramClass.getDeclaredField(
"CAMEL_NESTED_CLASS").get(null);
HashMap<String, Object> nestedParameters = new HashMap<>();
IntrospectionSupport.getProperties(value, nestedParameters,
null, false);
Object nestedProperty = nestedClass.newInstance();
IntrospectionSupport.setProperties(camelContext,
camelContext.getTypeConverter(), nestedProperty,
nestedParameters);
entry.setValue(nestedProperty);
} catch (NoSuchFieldException e) {
}
}
}
IntrospectionSupport.setProperties(camelContext,
camelContext.getTypeConverter(), component, parameters);
return component;
}
public static class Condition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(
ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean groupEnabled = isEnabled(conditionContext,
"camel.component.", true);
ConditionMessage.Builder message = ConditionMessage
.forCondition("camel.component.ahc");
if (isEnabled(conditionContext, "camel.component.ahc.",
groupEnabled)) {
return ConditionOutcome.match(message.because("enabled"));
}
return ConditionOutcome.noMatch(message.because("not enabled"));
}
private boolean isEnabled(
org.springframework.context.annotation.ConditionContext context,
java.lang.String prefix, boolean defaultValue) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), prefix);
return resolver.getProperty("enabled", Boolean.class, defaultValue);
}
}
} | lburgazzoli/apache-camel | platforms/spring-boot/components-starter/camel-ahc-starter/src/main/java/org/apache/camel/component/ahc/springboot/AhcComponentAutoConfiguration.java | Java | apache-2.0 | 5,409 |
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.loader.tools;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link Layouts}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class LayoutsTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void jarFile() throws Exception {
assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("te.st.jar")))
.isInstanceOf(Layouts.Jar.class);
}
@Test
public void warFile() throws Exception {
assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("te.st.war")))
.isInstanceOf(Layouts.War.class);
}
@Test
public void unknownFile() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Unable to deduce layout for 'test.txt'");
Layouts.forFile(new File("test.txt"));
}
@Test
public void jarLayout() throws Exception {
Layout layout = new Layouts.Jar();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
.isEqualTo("BOOT-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
.isEqualTo("BOOT-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
.isEqualTo("BOOT-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
.isEqualTo("BOOT-INF/lib/");
}
@Test
public void warLayout() throws Exception {
Layout layout = new Layouts.War();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
.isEqualTo("WEB-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
.isEqualTo("WEB-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
.isEqualTo("WEB-INF/lib-provided/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
.isEqualTo("WEB-INF/lib/");
}
}
| sebastiankirsch/spring-boot | spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java | Java | apache-2.0 | 3,110 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.visor.debug;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.management.MonitorInfo;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.visor.VisorDataTransferObjectInput;
import org.apache.ignite.internal.visor.VisorDataTransferObjectOutput;
/**
* Data transfer object for {@link MonitorInfo}.
*/
public class VisorThreadMonitorInfo extends VisorThreadLockInfo {
/** */
private static final long serialVersionUID = 0L;
/** Stack depth. */
private int stackDepth;
/** Stack frame. */
private StackTraceElement stackFrame;
/**
* Default constructor.
*/
public VisorThreadMonitorInfo() {
// No-op.
}
/**
* Create data transfer object for given monitor info.
*
* @param mi Monitoring info.
*/
public VisorThreadMonitorInfo(MonitorInfo mi) {
super(mi);
stackDepth = mi.getLockedStackDepth();
stackFrame = mi.getLockedStackFrame();
}
/**
* @return Stack depth.
*/
public int getStackDepth() {
return stackDepth;
}
/**
* @return Stack frame.
*/
public StackTraceElement getStackFrame() {
return stackFrame;
}
/** {@inheritDoc} */
@Override public byte getProtocolVersion() {
return 1;
}
/** {@inheritDoc} */
@Override protected void writeExternalData(ObjectOutput out) throws IOException {
try (VisorDataTransferObjectOutput dtout = new VisorDataTransferObjectOutput(out)) {
dtout.writeByte(super.getProtocolVersion());
super.writeExternalData(dtout);
}
out.writeInt(stackDepth);
out.writeObject(stackFrame);
}
/** {@inheritDoc} */
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
try (VisorDataTransferObjectInput dtin = new VisorDataTransferObjectInput(in)) {
super.readExternalData(dtin.readByte(), dtin);
}
stackDepth = in.readInt();
stackFrame = (StackTraceElement)in.readObject();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(VisorThreadMonitorInfo.class, this);
}
}
| irudyak/ignite | modules/core/src/main/java/org/apache/ignite/internal/visor/debug/VisorThreadMonitorInfo.java | Java | apache-2.0 | 3,156 |
/*
* Copyright 2015 NAVER Corp.
*
* 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.navercorp.pinpoint.plugin.mybatis;
import com.navercorp.pinpoint.common.Version;
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
import org.junit.runner.RunWith;
/**
* Tests against mybatis-spring 1.1.x (1.1.x requires mybatis 3.1.0 or higher)
* Prior versions do not handle mocked SqlSession proxies well.
*
* @author HyunGil Jeong
*/
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent("agent/target/pinpoint-agent-" + Version.VERSION)
@Dependency({ "org.mybatis:mybatis-spring:[1.1.0,1.1.max)", "org.mybatis:mybatis:3.2.7",
"org.springframework:spring-jdbc:[4.1.7.RELEASE]", "org.mockito:mockito-all:1.8.4" })
public class SqlSessionTemplate_1_1_x_IT extends SqlSessionTemplateITBase {
}
| dawidmalina/pinpoint | agent/src/test/java/com/navercorp/pinpoint/plugin/mybatis/SqlSessionTemplate_1_1_x_IT.java | Java | apache-2.0 | 1,447 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.rest;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.junit.Test;
/**
*
*/
public class JettyRestProcessorSignedSelfTest extends JettyRestProcessorAbstractSelfTest {
/** */
protected static final String REST_SECRET_KEY = "secret-key";
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
assert cfg.getConnectorConfiguration() != null;
cfg.getConnectorConfiguration().setSecretKey(REST_SECRET_KEY);
return cfg;
}
/** {@inheritDoc} */
@Override protected int restPort() {
return 8092;
}
/**
* @throws Exception If failed.
*/
@Test
public void testUnauthorized() throws Exception {
String addr = "http://" + LOC_HOST + ":" + restPort() + "/ignite?cacheName=default&cmd=top";
URL url = new URL(addr);
URLConnection conn = url.openConnection();
// Request has not been signed.
conn.connect();
assert ((HttpURLConnection)conn).getResponseCode() == 401;
// Request with authentication info.
addr = "http://" + LOC_HOST + ":" + restPort() + "/ignite?cacheName=default&cmd=top";
url = new URL(addr);
conn = url.openConnection();
conn.setRequestProperty("X-Signature", signature());
conn.connect();
assertEquals(200, ((HttpURLConnection)conn).getResponseCode());
}
/** {@inheritDoc} */
@Override protected String signature() throws Exception {
long ts = U.currentTimeMillis();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
String s = ts + ":" + REST_SECRET_KEY;
md.update(s.getBytes());
String hash = Base64.getEncoder().encodeToString(md.digest());
return ts + ":" + hash;
}
catch (NoSuchAlgorithmException e) {
throw new Exception("Failed to create authentication signature.", e);
}
}
}
| NSAmelchev/ignite | modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/JettyRestProcessorSignedSelfTest.java | Java | apache-2.0 | 3,215 |
/*
*
* 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.proton.amqp;
public final class UnsignedShort extends Number implements Comparable<UnsignedShort>
{
private final short _underlying;
private static final UnsignedShort[] cachedValues = new UnsignedShort[256];
public static final UnsignedShort MAX_VALUE = new UnsignedShort((short) -1);
static
{
for(short i = 0; i < 256; i++)
{
cachedValues[i] = new UnsignedShort(i);
}
}
public UnsignedShort(short underlying)
{
_underlying = underlying;
}
public short shortValue()
{
return _underlying;
}
@Override
public int intValue()
{
return _underlying & 0xFFFF;
}
@Override
public long longValue()
{
return ((long) _underlying) & 0xFFFFl;
}
@Override
public float floatValue()
{
return (float) intValue();
}
@Override
public double doubleValue()
{
return (double) intValue();
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
UnsignedShort that = (UnsignedShort) o;
if (_underlying != that._underlying)
{
return false;
}
return true;
}
public int compareTo(UnsignedShort o)
{
return Integer.signum(intValue() - o.intValue());
}
@Override
public int hashCode()
{
return _underlying;
}
@Override
public String toString()
{
return String.valueOf(longValue());
}
public static UnsignedShort valueOf(short underlying)
{
if((underlying & 0xFF00) == 0)
{
return cachedValues[underlying];
}
else
{
return new UnsignedShort(underlying);
}
}
public static UnsignedShort valueOf(final String value)
{
int intVal = Integer.parseInt(value);
if(intVal < 0 || intVal >= (1<<16))
{
throw new NumberFormatException("Value \""+value+"\" lies outside the range [" + 0 + "-" + (1<<16) +").");
}
return valueOf((short)intVal);
}
}
| dcristoloveanu/qpid-proton | proton-j/src/main/java/org/apache/qpid/proton/amqp/UnsignedShort.java | Java | apache-2.0 | 3,103 |
package org.jbehave.example.spring.security.steps;
import java.util.List;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.model.ExamplesTable;
import org.jbehave.core.steps.Parameters;
import org.jbehave.example.spring.security.dao.OrganizationDao;
import org.jbehave.example.spring.security.dao.UserDao;
import org.jbehave.example.spring.security.domain.Organization;
import org.jbehave.example.spring.security.domain.User;
import org.jbehave.example.spring.security.domain.UserBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("userSteps")
public class UserSteps {
@Autowired
private UserDao userDao;
@Autowired
private OrganizationDao organizationDao;
@Given("a user for $orgName with username $username and password $password")
public void createUserWithUsernameAndPassword(String orgName, String username, String password) {
Organization org = organizationDao.findByName(orgName);
User user = new User();
user.setOrganization(org);
user.setUsername(username);
user.setPasswordCleartext(password);
userDao.persist(user);
}
@Given("the users for $orgName: $userTable")
public void createUsersFromTable(String orgName, ExamplesTable table) {
Organization org = organizationDao.findByName(orgName);
List<Parameters> parametersList = table.getRowsAsParameters(true);
for (Parameters parameters : parametersList) {
userDao.persist(new UserBuilder(org, parameters, table.getHeaders()).build());
}
}
@Given("user for $orgName $username is disabled")
public void setUserDisabled(String orgName, String username) {
Organization org = organizationDao.findByName(orgName);
User user = userDao.findUserByOrganizationAndUsername(org.getId(), username);
user.setEnabled(false);
userDao.persist(user);
}
@Given("user for $orgName $username is enabled")
public void setUserEnabled(String orgName, String username) {
Organization org = organizationDao.findByName(orgName);
User user = userDao.findUserByOrganizationAndUsername(org.getId(), username);
user.setEnabled(true);
userDao.persist(user);
}
@Given("user for $orgName $username is expired")
public void setUserExpired(String orgName, String username) {
Organization org = organizationDao.findByName(orgName);
User user = userDao.findUserByOrganizationAndUsername(org.getId(), username);
user.setExpired(true);
userDao.persist(user);
}
}
| sischnei/jbehave-core | examples/spring-security/src/main/java/org/jbehave/example/spring/security/steps/UserSteps.java | Java | bsd-3-clause | 2,537 |
package drake.util;
import java.io.*;
import java.lang.*;
import java.lang.reflect.*;
import lcm.lcm.*;
/**
* Monitors a particular lcm message type (specified in the constructor)
* and maintains the most up-to-date instance of that type.
*
* The lcm message type must have a .timestamp field.
% If messages arrive out of order, it will keep the message with
* the largest timestamp. If no message is received for timeout seconds
* then the timestamp history is reset (e.g, it's assumed that the channel
* went dead and so accepts a time starting back at zero).
* The default value of this timeout is 1 second.
*
* Note that this is implemented with reflection instead of
* generics (e.g. MessageMonitor<lcmtype>) because the binding needs to
* happen at run-time (e.g. from MATLAB).
*
**/
public class MessageMonitor implements LCMSubscriber
{
long m_last_timestamp;
long m_time_of_last_message;
long m_reset_time=1000;
Field m_timestamp_field;
byte[] m_data;
Constructor<?> m_lcmtype_constructor=null;
boolean m_has_new_message = false;
public MessageMonitor(Class<?> lcmtype_class, String timestamp_field)
{
m_last_timestamp = -m_reset_time;
m_time_of_last_message = System.currentTimeMillis();
m_data = null;
boolean hasTimestamp = true;
try {
m_timestamp_field = lcmtype_class.getField(timestamp_field);
} catch (NoSuchFieldException ex) {
hasTimestamp = false;
}
if (m_timestamp_field==null || hasTimestamp==false) {
System.out.println("couldn't find the timestamp field '"+timestamp_field+"' in this LCM type");
for (Field field : lcmtype_class.getFields()) {
System.out.printf("Field name: %s%n", field.getName());
}
}
if (m_timestamp_field.getType().equals(Long.TYPE)==false) {
System.out.println("timestamp field is a "+m_timestamp_field.toString());
System.out.println("timestamp field must be a long");
}
try {
Class[] params = new Class[1];
params[0]=byte[].class;
m_lcmtype_constructor = lcmtype_class.getConstructor(params);
} catch (NoSuchMethodException ex) {
System.out.println("couldn't find constructor");
}
}
public MessageMonitor(LCMEncodable lcmtype, String timestamp_field)
{
this(lcmtype.getClass(),timestamp_field);
}
public void setResetTime(long ms)
{
m_reset_time = ms;
}
public synchronized void messageReceived(LCM lcm, String channel, LCMDataInputStream dins)
{
try {
byte[] data = new byte[dins.available()];
dins.readFully(data);
Object msg = m_lcmtype_constructor.newInstance(data);
long timestamp = m_timestamp_field.getLong(msg);
long systime = System.currentTimeMillis();
// include a 1 second timeout
if (timestamp>=m_last_timestamp || systime-m_time_of_last_message>=m_reset_time) {
m_data = data.clone();
m_has_new_message = true;
m_last_timestamp = timestamp;
// System.out.println(timestamp);
}
m_time_of_last_message = systime;
notifyAll();
} catch (IOException ex) {
System.out.println("MessageMonitor " + ex + " on channel " + channel);
} catch (InstantiationException ex) {
System.out.println("MessageMonitor " + ex + " on channel " + channel);
} catch (IllegalAccessException ex) {
System.out.println("MessageMonitor " + ex + " on channel " + channel);
} catch (InvocationTargetException ex) {
System.out.println("MessageMonitor " + ex + " on channel " + channel);
}
}
public synchronized byte[] getNextMessage(long timeout_ms)
{
if (m_has_new_message) {
m_has_new_message = false;
return m_data;
}
if(timeout_ms == 0)
return null;
try {
if(timeout_ms > 0)
wait(timeout_ms);
else
wait();
if (m_has_new_message) {
m_has_new_message = false;
return m_data;
}
} catch (InterruptedException ex) { }
return null;
}
public synchronized byte[] getNextMessage()
{
return getNextMessage(-1);
}
public synchronized long getLastTimestamp()
{
return m_last_timestamp;
}
public synchronized void waitUntilTimestamp(long timestamp)
{
try {
while (m_last_timestamp<timestamp)
wait();
} catch (InterruptedException ex) {}
}
public synchronized boolean waitUntilTimestamp(long timestamp, long timeout_ms)
{
if (m_last_timestamp>=timestamp)
return true;
try {
wait(timeout_ms);
} catch (InterruptedException ex) {}
// System.out.println(m_last_timestamp-timestamp);
return (m_last_timestamp>=timestamp);
}
public synchronized byte[] getMessage()
{
m_has_new_message = false;
return m_data;
}
public synchronized void markAsRead()
{
m_has_new_message = false;
}
public synchronized void markAsReadBefore(long timestamp)
{
if (m_last_timestamp<timestamp)
m_has_new_message = false;
}
/*
public static void main(String[] args) throws InterruptedException
{
MessageMonitor m = new MessageMonitor(new drc.robot_state_t(),"utime");
LCM lcm = LCM.getSingleton();
lcm.subscribe("EST_ROBOT_STATE",m);
while(true)
Thread.sleep(1000);
}
*/
}
| tkoolen/drake | util/MessageMonitor.java | Java | bsd-3-clause | 5,360 |
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.components.grid;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.vaadin.testbench.parallel.TestCategory;
import com.vaadin.tests.tb3.SingleBrowserTest;
@TestCategory("grid")
public class GridWithoutRendererTest extends SingleBrowserTest {
@Test
public void ensureNoError() {
openTestURL();
// WebElement errorIndicator = findElement(By
// .cssSelector("v-error-indicator"));
// System.out.println(errorIndicator);
List<WebElement> errorIndicator = findElements(By
.xpath("//span[@class='v-errorindicator']"));
Assert.assertTrue("There should not be an error indicator",
errorIndicator.isEmpty());
}
}
| jdahlstrom/vaadin.react | uitest/src/test/java/com/vaadin/tests/components/grid/GridWithoutRendererTest.java | Java | apache-2.0 | 1,427 |
/*
* 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.jackrabbit.oak.segment.data;
public class RecordIdData {
public static final int BYTES = Short.BYTES + Integer.BYTES;
private final int segmentReference;
private final int recordNumber;
RecordIdData(int segmentReference, int recordNumber) {
this.segmentReference = segmentReference;
this.recordNumber = recordNumber;
}
public int getSegmentReference() {
return segmentReference;
}
public int getRecordNumber() {
return recordNumber;
}
}
| anchela/jackrabbit-oak | oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/data/RecordIdData.java | Java | apache-2.0 | 1,336 |
/*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* 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.querydsl.spatial;
import org.geolatte.geom.LineString;
import com.querydsl.core.types.Expression;
/**
* A LinearRing is a LineString that is both closed and simple.
*
* @author tiwe
*
* @param <T>
*/
public abstract class LinearRingExpression<T extends LineString> extends LineStringExpression<T> {
private static final long serialVersionUID = -759466658721392938L;
public LinearRingExpression(Expression<T> mixin) {
super(mixin);
}
}
| balazs-zsoldos/querydsl | querydsl-spatial/src/main/java/com/querydsl/spatial/LinearRingExpression.java | Java | apache-2.0 | 1,102 |
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.common.net.http.handlers;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.twitter.common.base.ExceptionalSupplier;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A servlet that provides a crude mechanism for monitoring a service's health. If the servlet
* returns {@link #IS_HEALTHY} then the containing service should be deemed healthy.
*
* @author John Sirois
*/
public class HealthHandler extends HttpServlet {
/**
* A {@literal @Named} binding key for the Healthz servlet health checker.
*/
public static final String HEALTH_CHECKER_KEY =
"com.twitter.common.net.http.handlers.Healthz.checker";
/**
* The plain text response string this servlet returns in the body of its responses to health
* check requests when its containing service is healthy.
*/
public static final String IS_HEALTHY = "OK";
private static final String IS_NOT_HEALTHY = "SICK";
private static final Logger LOG = Logger.getLogger(HealthHandler.class.getName());
private final ExceptionalSupplier<Boolean, ?> healthChecker;
/**
* Constructs a new Healthz that uses the given {@code healthChecker} to determine current health
* of the service for at the point in time of each GET request. The given {@code healthChecker}
* should return {@code true} if the service is healthy and {@code false} otherwise. If the
* {@code healthChecker} returns null or throws the service is considered unhealthy.
*
* @param healthChecker a supplier that is called to perform a health check
*/
@Inject
public HealthHandler(@Named(HEALTH_CHECKER_KEY) ExceptionalSupplier<Boolean, ?> healthChecker) {
this.healthChecker = Preconditions.checkNotNull(healthChecker);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
try {
writer.println(Boolean.TRUE.equals(healthChecker.get()) ? IS_HEALTHY : IS_NOT_HEALTHY);
} catch (Exception e) {
writer.println(IS_NOT_HEALTHY);
LOG.log(Level.WARNING, "Health check failed.", e);
}
}
}
| foursquare/commons-old | src/java/com/twitter/common/net/http/handlers/HealthHandler.java | Java | apache-2.0 | 3,421 |
/*<license>
Copyright 2008 - $Date$ by PeopleWare n.v..
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.
</license>*/
package org.ppwcode.util.serialization_I.teststubsB;
public class ExternalizableSuperStub {
public final String getProperty1S() {
return $property1;
}
public final void setProperty1S(String property) {
$property1 = property;
}
private String $property1;
}
| jandppw/ppwcode-recovered-from-google-code | java/util/serialization/trunk/src/test/java/org/ppwcode/util/serialization_I/teststubsB/ExternalizableSuperStub.java | Java | apache-2.0 | 876 |
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.tooltip;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.tests.tb3.TooltipTest;
/**
* Tests that tooltip sizes do not change when moving between adjacent elements
*
* @author Vaadin Ltd
*/
public class ButtonTooltipsTest extends TooltipTest {
@Test
public void tooltipSizeWhenMovingBetweenElements() throws Exception {
openTestURL();
WebElement buttonOne = $(ButtonElement.class).caption("One").first();
WebElement buttonTwo = $(ButtonElement.class).caption("Two").first();
checkTooltip(buttonOne, ButtonTooltips.longDescription);
int originalWidth = getTooltipElement().getSize().getWidth();
int originalHeight = getTooltipElement().getSize().getHeight();
clearTooltip();
checkTooltip(buttonTwo, ButtonTooltips.shortDescription);
moveMouseTo(buttonOne, 5, 5);
sleep(100);
assertThat(getTooltipElement().getSize().getWidth(), is(originalWidth));
assertThat(getTooltipElement().getSize().getHeight(),
is(originalHeight));
}
}
| jdahlstrom/vaadin.react | uitest/src/test/java/com/vaadin/tests/tooltip/ButtonTooltipsTest.java | Java | apache-2.0 | 1,849 |
package org.zstack.test.storage.snapshot;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.storage.backup.BackupStorageInventory;
import org.zstack.header.storage.snapshot.*;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.volume.VolumeVO;
import org.zstack.simulator.storage.primary.nfs.NfsPrimaryStorageSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
/*
* 1. take 4 snapshot from vm's root volume
* 2. backup snapshot 4 to sftp
* 3. backup snapshot 4 to sftp1
*
* confirm snapshot 4 is backed up on sftp and sftp1, others are not
*/
public class TestSnapshotOnKvm26 {
CLogger logger = Utils.getLogger(TestSnapshotOnKvm26.class);
Deployer deployer;
Api api;
ComponentLoader loader;
CloudBus bus;
DatabaseFacade dbf;
SessionInventory session;
NfsPrimaryStorageSimulatorConfig nfsConfig;
@Before
public void setUp() throws Exception {
DBUtil.reDeployDB();
WebBeanConstructor con = new WebBeanConstructor();
deployer = new Deployer("deployerXml/kvm/TestTakeSnapshotOnKvm12.xml", con);
deployer.addSpringConfig("KVMRelated.xml");
deployer.build();
api = deployer.getApi();
loader = deployer.getComponentLoader();
bus = loader.getComponent(CloudBus.class);
dbf = loader.getComponent(DatabaseFacade.class);
nfsConfig = loader.getComponent(NfsPrimaryStorageSimulatorConfig.class);
session = api.loginAsAdmin();
}
private void fullSnapshot(VolumeSnapshotInventory inv, int distance) {
Assert.assertEquals(VolumeSnapshotState.Enabled.toString(), inv.getState());
Assert.assertEquals(VolumeSnapshotStatus.Ready.toString(), inv.getStatus());
VolumeVO vol = dbf.findByUuid(inv.getVolumeUuid(), VolumeVO.class);
VolumeSnapshotVO svo = dbf.findByUuid(inv.getUuid(), VolumeSnapshotVO.class);
Assert.assertNotNull(svo);
Assert.assertFalse(svo.isFullSnapshot());
Assert.assertTrue(svo.isLatest());
Assert.assertNull(svo.getParentUuid());
Assert.assertEquals(distance, svo.getDistance());
Assert.assertEquals(vol.getPrimaryStorageUuid(), svo.getPrimaryStorageUuid());
Assert.assertNotNull(svo.getPrimaryStorageInstallPath());
VolumeSnapshotTreeVO cvo = dbf.findByUuid(svo.getTreeUuid(), VolumeSnapshotTreeVO.class);
Assert.assertNotNull(cvo);
Assert.assertTrue(cvo.isCurrent());
}
private void deltaSnapshot(VolumeSnapshotInventory inv, int distance) {
Assert.assertEquals(VolumeSnapshotState.Enabled.toString(), inv.getState());
Assert.assertEquals(VolumeSnapshotStatus.Ready.toString(), inv.getStatus());
VolumeVO vol = dbf.findByUuid(inv.getVolumeUuid(), VolumeVO.class);
VolumeSnapshotVO svo = dbf.findByUuid(inv.getUuid(), VolumeSnapshotVO.class);
Assert.assertNotNull(svo);
Assert.assertFalse(svo.isFullSnapshot());
Assert.assertTrue(svo.isLatest());
Assert.assertNotNull(svo.getParentUuid());
Assert.assertEquals(distance, svo.getDistance());
Assert.assertEquals(vol.getPrimaryStorageUuid(), svo.getPrimaryStorageUuid());
Assert.assertNotNull(svo.getPrimaryStorageInstallPath());
VolumeSnapshotTreeVO cvo = dbf.findByUuid(svo.getTreeUuid(), VolumeSnapshotTreeVO.class);
Assert.assertNotNull(cvo);
Assert.assertTrue(cvo.isCurrent());
Assert.assertEquals(svo.getTreeUuid(), cvo.getUuid());
}
@Test
public void test() throws ApiSenderException, InterruptedException {
BackupStorageInventory bs = deployer.backupStorages.get("sftp");
BackupStorageInventory bs1 = deployer.backupStorages.get("sftp1");
VmInstanceInventory vm = deployer.vms.get("TestVm");
String volUuid = vm.getRootVolumeUuid();
VolumeSnapshotInventory inv = api.createSnapshot(volUuid);
fullSnapshot(inv, 0);
inv = api.createSnapshot(volUuid);
deltaSnapshot(inv, 1);
VolumeSnapshotInventory inv2 = api.createSnapshot(volUuid);
deltaSnapshot(inv2, 2);
VolumeSnapshotInventory inv3 = api.createSnapshot(volUuid);
deltaSnapshot(inv3, 3);
inv3 = api.backupSnapshot(inv3.getUuid(), bs.getUuid());
inv3 = api.backupSnapshot(inv3.getUuid(), bs1.getUuid());
long count = dbf.count(VolumeSnapshotBackupStorageRefVO.class);
Assert.assertEquals(5, count);
SimpleQuery<VolumeSnapshotBackupStorageRefVO> q = dbf.createQuery(VolumeSnapshotBackupStorageRefVO.class);
q.add(VolumeSnapshotBackupStorageRefVO_.installPath, SimpleQuery.Op.NOT_NULL);
count = q.count();
Assert.assertEquals(5, count);
}
}
| zstackorg/zstack | test/src/test/java/org/zstack/test/storage/snapshot/TestSnapshotOnKvm26.java | Java | apache-2.0 | 5,243 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstarts.ear.client;
import javax.ejb.Local;
/**
* @author bmaxwell
*
*/
@Local
public interface GreeterEJBLocal {
public String sayHello(String name) throws GreeterException;
}
| fellipecm/jboss-eap-quickstarts | ejb-throws-exception/ejb-api/src/main/java/org/jboss/as/quickstarts/ear/client/GreeterEJBLocal.java | Java | apache-2.0 | 1,011 |
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui.components.calendar;
import java.util.Date;
import java.util.Map;
import com.vaadin.event.dd.DropTarget;
import com.vaadin.event.dd.TargetDetailsImpl;
import com.vaadin.ui.Calendar;
/**
* Drop details for {@link com.vaadin.ui.addon.calendar.ui.Calendar Calendar}.
* When something is dropped on the Calendar, this class contains the specific
* details of the drop point. Specifically, this class gives access to the date
* where the drop happened. If the Calendar was in weekly mode, the date also
* includes the start time of the slot.
*
* @since 7.1
* @author Vaadin Ltd.
*/
@SuppressWarnings("serial")
public class CalendarTargetDetails extends TargetDetailsImpl {
private boolean hasDropTime;
public CalendarTargetDetails(Map<String, Object> rawDropData,
DropTarget dropTarget) {
super(rawDropData, dropTarget);
}
/**
* @return true if {@link #getDropTime()} will return a date object with the
* time set to the start of the time slot where the drop happened
*/
public boolean hasDropTime() {
return hasDropTime;
}
/**
* Does the dropped item have a time associated with it
*
* @param hasDropTime
*/
public void setHasDropTime(boolean hasDropTime) {
this.hasDropTime = hasDropTime;
}
/**
* @return the date where the drop happened
*/
public Date getDropTime() {
if (hasDropTime) {
return (Date) getData("dropTime");
} else {
return (Date) getData("dropDay");
}
}
/**
* @return the {@link com.vaadin.ui.addon.calendar.ui.Calendar Calendar}
* instance which was the target of the drop
*/
public Calendar getTargetCalendar() {
return (Calendar) getTarget();
}
}
| jdahlstrom/vaadin.react | server/src/main/java/com/vaadin/ui/components/calendar/CalendarTargetDetails.java | Java | apache-2.0 | 2,432 |
package com.fsck.k9.helper;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.R;
import com.fsck.k9.activity.FolderInfoHolder;
import com.fsck.k9.activity.MessageInfoHolder;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mailstore.LocalMessage;
public class MessageHelper {
/**
* If the number of addresses exceeds this value the addresses aren't
* resolved to the names of Android contacts.
*
* <p>
* TODO: This number was chosen arbitrarily and should be determined by
* performance tests.
* </p>
*
* @see #toFriendly(Address[], com.fsck.k9.helper.Contacts)
*/
private static final int TOO_MANY_ADDRESSES = 50;
private static MessageHelper sInstance;
public synchronized static MessageHelper getInstance(final Context context) {
if (sInstance == null) {
sInstance = new MessageHelper(context);
}
return sInstance;
}
private Context mContext;
private MessageHelper(final Context context) {
mContext = context;
}
public void populate(final MessageInfoHolder target,
final LocalMessage message,
final FolderInfoHolder folder,
Account account) {
final Contacts contactHelper = K9.showContactName() ? Contacts.getInstance(mContext) : null;
target.message = message;
target.compareArrival = message.getInternalDate();
target.compareDate = message.getSentDate();
if (target.compareDate == null) {
target.compareDate = message.getInternalDate();
}
target.folder = folder;
target.read = message.isSet(Flag.SEEN);
target.answered = message.isSet(Flag.ANSWERED);
target.forwarded = message.isSet(Flag.FORWARDED);
target.flagged = message.isSet(Flag.FLAGGED);
Address[] addrs = message.getFrom();
if (addrs.length > 0 && account.isAnIdentity(addrs[0])) {
CharSequence to = toFriendly(message.getRecipients(RecipientType.TO), contactHelper);
target.compareCounterparty = to.toString();
target.sender = new SpannableStringBuilder(mContext.getString(R.string.message_to_label)).append(to);
} else {
target.sender = toFriendly(addrs, contactHelper);
target.compareCounterparty = target.sender.toString();
}
if (addrs.length > 0) {
target.senderAddress = addrs[0].getAddress();
} else {
// a reasonable fallback "whomever we were corresponding with
target.senderAddress = target.compareCounterparty;
}
target.uid = message.getUid();
target.account = message.getFolder().getAccountUuid();
target.uri = message.getUri();
}
public CharSequence getDisplayName(Account account, Address[] fromAddrs, Address[] toAddrs) {
final Contacts contactHelper = K9.showContactName() ? Contacts.getInstance(mContext) : null;
CharSequence displayName;
if (fromAddrs.length > 0 && account.isAnIdentity(fromAddrs[0])) {
CharSequence to = toFriendly(toAddrs, contactHelper);
displayName = new SpannableStringBuilder(
mContext.getString(R.string.message_to_label)).append(to);
} else {
displayName = toFriendly(fromAddrs, contactHelper);
}
return displayName;
}
public boolean toMe(Account account, Address[] toAddrs) {
for (Address address : toAddrs) {
if (account.isAnIdentity(address)) {
return true;
}
}
return false;
}
/**
* Returns the name of the contact this email address belongs to if
* the {@link Contacts contacts} parameter is not {@code null} and a
* contact is found. Otherwise the personal portion of the {@link Address}
* is returned. If that isn't available either, the email address is
* returned.
*
* @param address An {@link com.fsck.k9.mail.Address}
* @param contacts A {@link Contacts} instance or {@code null}.
* @return A "friendly" name for this {@link Address}.
*/
public static CharSequence toFriendly(Address address, Contacts contacts) {
return toFriendly(address,contacts,
K9.showCorrespondentNames(),
K9.changeContactNameColor(),
K9.getContactNameColor());
}
public static CharSequence toFriendly(Address[] addresses, Contacts contacts) {
if (addresses == null) {
return null;
}
if (addresses.length >= TOO_MANY_ADDRESSES) {
// Don't look up contacts if the number of addresses is very high.
contacts = null;
}
SpannableStringBuilder sb = new SpannableStringBuilder();
for (int i = 0; i < addresses.length; i++) {
sb.append(toFriendly(addresses[i], contacts));
if (i < addresses.length - 1) {
sb.append(',');
}
}
return sb;
}
/* package, for testing */ static CharSequence toFriendly(Address address, Contacts contacts,
boolean showCorrespondentNames,
boolean changeContactNameColor,
int contactNameColor) {
if (!showCorrespondentNames) {
return address.getAddress();
} else if (contacts != null) {
final String name = contacts.getNameForAddress(address.getAddress());
// TODO: The results should probably be cached for performance reasons.
if (name != null) {
if (changeContactNameColor) {
final SpannableString coloredName = new SpannableString(name);
coloredName.setSpan(new ForegroundColorSpan(contactNameColor),
0,
coloredName.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
return coloredName;
} else {
return name;
}
}
}
return (!TextUtils.isEmpty(address.getPersonal())) ? address.getPersonal() : address.getAddress();
}
}
| indus1/k-9 | k9mail/src/main/java/com/fsck/k9/helper/MessageHelper.java | Java | apache-2.0 | 6,703 |
/*
* 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.api.common.typeutils.base;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.MemorySegment;
import java.io.IOException;
import java.time.LocalTime;
@Internal
public final class LocalTimeComparator extends BasicTypeComparator<LocalTime> {
private static final long serialVersionUID = 1L;
public LocalTimeComparator(boolean ascending) {
super(ascending);
}
@Override
public int compareSerialized(DataInputView firstSource, DataInputView secondSource)
throws IOException {
return compareSerializedLocalTime(firstSource, secondSource, ascendingComparison);
}
@Override
public boolean supportsNormalizedKey() {
return true;
}
@Override
public int getNormalizeKeyLen() {
return 7;
}
@Override
public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
return keyBytes < getNormalizeKeyLen();
}
@Override
public void putNormalizedKey(LocalTime record, MemorySegment target, int offset, int numBytes) {
putNormalizedKeyLocalTime(record, target, offset, numBytes);
}
@Override
public LocalTimeComparator duplicate() {
return new LocalTimeComparator(ascendingComparison);
}
// --------------------------------------------------------------------------------------------
// Static Helpers for Date Comparison
// --------------------------------------------------------------------------------------------
public static int compareSerializedLocalTime(
DataInputView firstSource, DataInputView secondSource, boolean ascendingComparison)
throws IOException {
int cmp = firstSource.readByte() - secondSource.readByte();
if (cmp == 0) {
cmp = firstSource.readByte() - secondSource.readByte();
if (cmp == 0) {
cmp = firstSource.readByte() - secondSource.readByte();
if (cmp == 0) {
cmp = firstSource.readInt() - secondSource.readInt();
}
}
}
return ascendingComparison ? cmp : -cmp;
}
public static void putNormalizedKeyLocalTime(
LocalTime record, MemorySegment target, int offset, int numBytes) {
int hour = record.getHour();
if (numBytes > 0) {
target.put(offset, (byte) (hour & 0xff - Byte.MIN_VALUE));
numBytes -= 1;
offset += 1;
}
int minute = record.getMinute();
if (numBytes > 0) {
target.put(offset, (byte) (minute & 0xff - Byte.MIN_VALUE));
numBytes -= 1;
offset += 1;
}
int second = record.getSecond();
if (numBytes > 0) {
target.put(offset, (byte) (second & 0xff - Byte.MIN_VALUE));
numBytes -= 1;
offset += 1;
}
int nano = record.getNano();
int unsignedNano = nano - Integer.MIN_VALUE;
if (numBytes >= 4) {
target.putIntBigEndian(offset, unsignedNano);
numBytes -= 4;
offset += 4;
} else if (numBytes > 0) {
for (int i = 0; numBytes > 0; numBytes--, i++) {
target.put(offset + i, (byte) (unsignedNano >>> ((3 - i) << 3)));
}
return;
}
for (int i = 0; i < numBytes; i++) {
target.put(offset + i, (byte) 0);
}
}
}
| apache/flink | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LocalTimeComparator.java | Java | apache-2.0 | 4,352 |
/*
* 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.test.optimizer.iterations;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.functions.CoGroupFunction;
import org.apache.flink.api.common.functions.FlatJoinFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.operators.util.FieldList;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.FunctionAnnotation.ForwardedFieldsFirst;
import org.apache.flink.api.java.functions.FunctionAnnotation.ForwardedFieldsSecond;
import org.apache.flink.api.java.operators.DeltaIteration;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.optimizer.dag.TempMode;
import org.apache.flink.optimizer.plan.DualInputPlanNode;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plan.SinkPlanNode;
import org.apache.flink.optimizer.plan.SourcePlanNode;
import org.apache.flink.optimizer.plan.WorksetIterationPlanNode;
import org.apache.flink.optimizer.plandump.PlanJSONDumpGenerator;
import org.apache.flink.optimizer.plantranslate.JobGraphGenerator;
import org.apache.flink.optimizer.util.CompilerTestBase;
import org.apache.flink.runtime.operators.DriverStrategy;
import org.apache.flink.runtime.operators.shipping.ShipStrategyType;
import org.apache.flink.runtime.operators.util.LocalStrategy;
import org.apache.flink.util.Collector;
import org.junit.Assert;
import org.junit.Test;
/** */
@SuppressWarnings("serial")
public class ConnectedComponentsCoGroupTest extends CompilerTestBase {
private static final String VERTEX_SOURCE = "Vertices";
private static final String ITERATION_NAME = "Connected Components Iteration";
private static final String EDGES_SOURCE = "Edges";
private static final String JOIN_NEIGHBORS_MATCH = "Join Candidate Id With Neighbor";
private static final String MIN_ID_AND_UPDATE = "Min Id and Update";
private static final String SINK = "Result";
private static final boolean PRINT_PLAN = false;
private final FieldList set0 = new FieldList(0);
@Test
public void testWorksetConnectedComponents() throws Exception {
Plan plan = getConnectedComponentsCoGroupPlan();
plan.setExecutionConfig(new ExecutionConfig());
OptimizedPlan optPlan = compileNoStats(plan);
OptimizerPlanNodeResolver or = getOptimizerPlanNodeResolver(optPlan);
if (PRINT_PLAN) {
PlanJSONDumpGenerator dumper = new PlanJSONDumpGenerator();
String json = dumper.getOptimizerPlanAsJSON(optPlan);
System.out.println(json);
}
SourcePlanNode vertexSource = or.getNode(VERTEX_SOURCE);
SourcePlanNode edgesSource = or.getNode(EDGES_SOURCE);
SinkPlanNode sink = or.getNode(SINK);
WorksetIterationPlanNode iter = or.getNode(ITERATION_NAME);
DualInputPlanNode neighborsJoin = or.getNode(JOIN_NEIGHBORS_MATCH);
DualInputPlanNode cogroup = or.getNode(MIN_ID_AND_UPDATE);
// --------------------------------------------------------------------
// Plan validation:
//
// We expect the plan to go with a sort-merge join, because the CoGroup
// sorts and the join in the successive iteration can re-exploit the sorting.
// --------------------------------------------------------------------
// test all drivers
Assert.assertEquals(DriverStrategy.NONE, sink.getDriverStrategy());
Assert.assertEquals(DriverStrategy.NONE, vertexSource.getDriverStrategy());
Assert.assertEquals(DriverStrategy.NONE, edgesSource.getDriverStrategy());
Assert.assertEquals(DriverStrategy.INNER_MERGE, neighborsJoin.getDriverStrategy());
Assert.assertEquals(set0, neighborsJoin.getKeysForInput1());
Assert.assertEquals(set0, neighborsJoin.getKeysForInput2());
Assert.assertEquals(DriverStrategy.CO_GROUP, cogroup.getDriverStrategy());
Assert.assertEquals(set0, cogroup.getKeysForInput1());
Assert.assertEquals(set0, cogroup.getKeysForInput2());
// test all the shipping strategies
Assert.assertEquals(ShipStrategyType.FORWARD, sink.getInput().getShipStrategy());
Assert.assertEquals(
ShipStrategyType.PARTITION_HASH,
iter.getInitialSolutionSetInput().getShipStrategy());
Assert.assertEquals(set0, iter.getInitialSolutionSetInput().getShipStrategyKeys());
Assert.assertEquals(
ShipStrategyType.PARTITION_HASH, iter.getInitialWorksetInput().getShipStrategy());
Assert.assertEquals(set0, iter.getInitialWorksetInput().getShipStrategyKeys());
Assert.assertEquals(
ShipStrategyType.FORWARD, neighborsJoin.getInput1().getShipStrategy()); // workset
Assert.assertEquals(
ShipStrategyType.PARTITION_HASH,
neighborsJoin.getInput2().getShipStrategy()); // edges
Assert.assertEquals(set0, neighborsJoin.getInput2().getShipStrategyKeys());
Assert.assertTrue(neighborsJoin.getInput2().getTempMode().isCached());
Assert.assertEquals(
ShipStrategyType.PARTITION_HASH, cogroup.getInput1().getShipStrategy()); // min id
Assert.assertEquals(
ShipStrategyType.FORWARD, cogroup.getInput2().getShipStrategy()); // solution set
// test all the local strategies
Assert.assertEquals(LocalStrategy.NONE, sink.getInput().getLocalStrategy());
Assert.assertEquals(
LocalStrategy.NONE, iter.getInitialSolutionSetInput().getLocalStrategy());
// the sort for the neighbor join in the first iteration is pushed out of the loop
Assert.assertEquals(LocalStrategy.SORT, iter.getInitialWorksetInput().getLocalStrategy());
Assert.assertEquals(
LocalStrategy.NONE, neighborsJoin.getInput1().getLocalStrategy()); // workset
Assert.assertEquals(
LocalStrategy.SORT, neighborsJoin.getInput2().getLocalStrategy()); // edges
Assert.assertEquals(LocalStrategy.SORT, cogroup.getInput1().getLocalStrategy());
Assert.assertEquals(
LocalStrategy.NONE, cogroup.getInput2().getLocalStrategy()); // solution set
// check the caches
Assert.assertTrue(TempMode.CACHED == neighborsJoin.getInput2().getTempMode());
JobGraphGenerator jgg = new JobGraphGenerator();
jgg.compileJobGraph(optPlan);
}
public static Plan getConnectedComponentsCoGroupPlan() throws Exception {
return connectedComponentsWithCoGroup(
new String[] {DEFAULT_PARALLELISM_STRING, IN_FILE, IN_FILE, OUT_FILE, "100"});
}
public static Plan connectedComponentsWithCoGroup(String[] args) throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(Integer.parseInt(args[0]));
DataSet<Tuple1<Long>> initialVertices =
env.readCsvFile(args[1]).types(Long.class).name(VERTEX_SOURCE);
DataSet<Tuple2<Long, Long>> edges =
env.readCsvFile(args[2]).types(Long.class, Long.class).name(EDGES_SOURCE);
DataSet<Tuple2<Long, Long>> verticesWithId =
initialVertices.flatMap(new DummyMapFunction());
DeltaIteration<Tuple2<Long, Long>, Tuple2<Long, Long>> iteration =
verticesWithId
.iterateDelta(verticesWithId, Integer.parseInt(args[4]), 0)
.name(ITERATION_NAME);
DataSet<Tuple2<Long, Long>> joinWithNeighbors =
iteration
.getWorkset()
.join(edges)
.where(0)
.equalTo(0)
.with(new DummyJoinFunction())
.name(JOIN_NEIGHBORS_MATCH);
DataSet<Tuple2<Long, Long>> minAndUpdate =
joinWithNeighbors
.coGroup(iteration.getSolutionSet())
.where(0)
.equalTo(0)
.with(new DummyCoGroupFunction())
.name(MIN_ID_AND_UPDATE);
iteration.closeWith(minAndUpdate, minAndUpdate).writeAsCsv(args[3]).name(SINK);
return env.createProgramPlan();
}
private static class DummyMapFunction
implements FlatMapFunction<Tuple1<Long>, Tuple2<Long, Long>> {
@Override
public void flatMap(Tuple1<Long> value, Collector<Tuple2<Long, Long>> out)
throws Exception {
// won't be executed
}
}
private static class DummyJoinFunction
implements FlatJoinFunction<
Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> {
@Override
public void join(
Tuple2<Long, Long> first,
Tuple2<Long, Long> second,
Collector<Tuple2<Long, Long>> out)
throws Exception {
// won't be executed
}
}
@ForwardedFieldsFirst("f0->f0")
@ForwardedFieldsSecond("f0->f0")
private static class DummyCoGroupFunction
implements CoGroupFunction<Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> {
@Override
public void coGroup(
Iterable<Tuple2<Long, Long>> first,
Iterable<Tuple2<Long, Long>> second,
Collector<Tuple2<Long, Long>> out)
throws Exception {
// won't be executed
}
}
}
| apache/flink | flink-tests/src/test/java/org/apache/flink/test/optimizer/iterations/ConnectedComponentsCoGroupTest.java | Java | apache-2.0 | 10,571 |
/*
* This file from
* https://github.com/addthis/stream-lib/blob/master/src/main/java/com/clearspring/analytics/stream/cardinality/HyperLogLog.java
*
* This class modified by Scouter-Project
* - original package : com.clearspring.analytics.stream.cardinality
* - remove implements : ICardinality, Serializable
* - add method : public boolean offer(long o)
* - remove classes : Builder, enum Format, HyperLogLogPlusMergeException, SerializationHolder
*
* ====================================
*
* Copyright (C) 2012 Clearspring Technologies, 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 scouter.server.util.cardinality;
import java.io.IOException;
import scouter.io.DataInputX;
import scouter.io.DataOutputX;
/**
* Java implementation of HyperLogLog (HLL) algorithm from this paper:
* <p/>
* http://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf
* <p/>
* HLL is an improved version of LogLog that is capable of estimating the
* cardinality of a set with accuracy = 1.04/sqrt(m) where m = 2^b. So we can
* control accuracy vs space usage by increasing or decreasing b.
* <p/>
* The main benefit of using HLL over LL is that it only requires 64% of the
* space that LL does to get the same accuracy.
* <p/>
* This implementation implements a single counter. If a large (millions) number
* of counters are required you may want to refer to:
* <p/>
* http://dsiutils.dsi.unimi.it/
* <p/>
* It has a more complex implementation of HLL that supports multiple counters
* in a single object, drastically reducing the java overhead from creating a
* large number of objects.
* <p/>
* This implementation leveraged a javascript implementation that Yammer has
* been working on:
* <p/>
* https://github.com/yammer/probablyjs
* <p>
* Note that this implementation does not include the long range correction
* function defined in the original paper. Empirical evidence shows that the
* correction function causes more harm than good.
* </p>
* <p/>
* <p>
* Users have different motivations to use different types of hashing functions.
* Rather than try to keep up with all available hash functions and to remove
* the concern of causing future binary incompatibilities this class allows
* clients to offer the value in hashed int or long form. This way clients are
* free to change their hash function on their own time line. We recommend using
* Google's Guava Murmur3_128 implementation as it provides good performance and
* speed when high precision is required. In our tests the 32bit MurmurHash
* function included in this project is faster and produces better results than
* the 32 bit murmur3 implementation google provides.
* </p>
*
*/
public class HyperLogLog {
/**
* It's is dirty flag to use any purpose
* #Scouter-Project
*/
public boolean dirty;
private final RegisterSet registerSet;
private final int log2m;
private final double alphaMM;
/**
* Create a new HyperLogLog instance using the specified standard deviation.
*
* @param rsd
* - the relative standard deviation for the counter. smaller
* values create counters that require more space.
*/
public HyperLogLog(double rsd) {
this(log2m(rsd));
}
private static int log2m(double rsd) {
return (int) (Math.log((1.106 / rsd) * (1.106 / rsd)) / Math.log(2));
}
private static double rsd(int log2m) {
return 1.106 / Math.sqrt(Math.exp(log2m * Math.log(2)));
}
private static void validateLog2m(int log2m) {
if (log2m < 0 || log2m > 30) {
throw new IllegalArgumentException("log2m argument is " + log2m + " and is outside the range [0, 30]");
}
}
/**
* Create a new HyperLogLog instance. The log2m parameter defines the
* accuracy of the counter. The larger the log2m the better the accuracy.
* <p/>
* accuracy = 1.04/sqrt(2^log2m)
*
* @param log2m
* - the number of bits to use as the basis for the HLL instance
*/
public HyperLogLog(int log2m) {
this(log2m, new RegisterSet(1 << log2m));
}
/**
* Creates a new HyperLogLog instance using the given registers. Used for
* unmarshalling a serialized instance and for merging multiple counters
* together.
*
* @param registerSet
* - the initial values for the register set
*/
@Deprecated
public HyperLogLog(int log2m, RegisterSet registerSet) {
validateLog2m(log2m);
this.registerSet = registerSet;
this.log2m = log2m;
int m = 1 << this.log2m;
alphaMM = getAlphaMM(log2m, m);
}
public boolean offerHashed(long hashedValue) {
// j becomes the binary address determined by the first b log2m of x
// j will be between 0 and 2^log2m
final int j = (int) (hashedValue >>> (Long.SIZE - log2m));
final int r = Long.numberOfLeadingZeros((hashedValue << this.log2m) | (1 << (this.log2m - 1)) + 1) + 1;
return registerSet.updateIfGreater(j, r);
}
public boolean offerHashed(int hashedValue) {
// j becomes the binary address determined by the first b log2m of x
// j will be between 0 and 2^log2m
final int j = hashedValue >>> (Integer.SIZE - log2m);
final int r = Integer.numberOfLeadingZeros((hashedValue << this.log2m) | (1 << (this.log2m - 1)) + 1) + 1;
return registerSet.updateIfGreater(j, r);
}
public boolean offer(Object o) {
final int x = MurmurHash.hash(o);
return offerHashed(x);
}
public boolean offer(long o) {
final int x = MurmurHash.hashLong(o);
return offerHashed(x);
}
public long cardinality() {
double registerSum = 0;
int count = registerSet.count;
double zeros = 0.0;
for (int j = 0; j < registerSet.count; j++) {
int val = registerSet.get(j);
registerSum += 1.0 / (1 << val);
if (val == 0) {
zeros++;
}
}
double estimate = alphaMM * (1 / registerSum);
if (estimate <= (5.0 / 2.0) * count) {
// Small Range Estimate
return Math.round(linearCounting(count, zeros));
} else {
return Math.round(estimate);
}
}
public int sizeof() {
return registerSet.size * 4;
}
/*
* This method is modified by Souter-project
*
*/
public byte[] getBytes() throws IOException {
DataOutputX out = new DataOutputX();
out.writeInt(log2m);
out.writeInt(registerSet.size);
for (int x : registerSet.readOnlyBits()) {
out.writeInt(x);
}
return out.toByteArray();
}
/**
* Add all the elements of the other set to this set.
* <p/>
* This operation does not imply a loss of precision.
*
* @param other
* A compatible Hyperloglog instance (same log2m)
* @throws CardinalityMergeException
* if other is not compatible
*/
public void addAll(HyperLogLog other) {
if (this.sizeof() != other.sizeof()) {
throw new RuntimeException("Cannot merge estimators of different sizes");
}
registerSet.merge(other.registerSet);
}
public HyperLogLog merge(HyperLogLog... estimators) {
HyperLogLog merged = new HyperLogLog(log2m, new RegisterSet(this.registerSet.count));
merged.addAll(this);
if (estimators == null) {
return merged;
}
for (HyperLogLog estimator : estimators) {
HyperLogLog hll = (HyperLogLog) estimator;
merged.addAll(hll);
}
return merged;
}
/*
* Initial code from HyperLogLog.Builder.build()
* by Scouter-Project
*/
public static HyperLogLog build(byte[] bytes) throws IOException {
DataInputX in = new DataInputX(bytes);
int log2m = in.readInt();
int n = in.readInt();
int[] ints = new int[n];
for (int i = 0; i < n; i++) {
ints[i] = in.readInt();
}
return new HyperLogLog(log2m, new RegisterSet(1 << log2m, ints));
}
protected static double getAlphaMM(final int p, final int m) {
// See the paper.
switch (p) {
case 4:
return 0.673 * m * m;
case 5:
return 0.697 * m * m;
case 6:
return 0.709 * m * m;
default:
return (0.7213 / (1 + 1.079 / m)) * m * m;
}
}
protected static double linearCounting(int m, double V) {
return m * Math.log(m / V);
}
}
| jahnaviancha/scouter | scouter.server/src/scouter/server/util/cardinality/HyperLogLog.java | Java | apache-2.0 | 8,459 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
package org.apache.ecs.xhtml;
import org.apache.ecs.Element;
import org.apache.ecs.KeyEvents;
import org.apache.ecs.MouseEvents;
import org.apache.ecs.MultiPartElement;
import org.apache.ecs.Printable;
/**
This class creates a <q> tag.
@version $Id: q.java,v 1.2 2006/07/30 00:54:02 jjanke Exp $
@author <a href="mailto:[email protected]">Stephan Nagy</a>
@author <a href="mailto:[email protected]">Jon S. Stevens</a>
@author <a href="mailto:[email protected]">Bojan Smojver</a>
*/
public class q extends MultiPartElement implements Printable, MouseEvents, KeyEvents
{
/**
*
*/
private static final long serialVersionUID = 2598898594639266579L;
/**
Private initialization routine.
*/
{
setElementType("q");
setCase(LOWERCASE);
setAttributeQuote(true);
}
/**
Basic constructor.
*/
public q()
{
}
/**
Basic constructor.
@param element Adds an Element to the element.
*/
public q(Element element)
{
addElement(element);
}
/**
Basic constructor.
@param element Adds an Element to the element.
*/
public q(String element)
{
addElement(element);
}
/**
Basic constructor.
@param element Adds an Element to the element.
@param cite sets the cite="" attribute.
*/
public q(Element element, String cite)
{
addElement(element);
setCite(cite);
}
/**
Basic constructor.
@param element Adds an Element to the element.
@param cite sets the cite="" attribute.
*/
public q(String element, String cite)
{
addElement(element);
setCite(cite);
}
/**
Basic constructor.
@param element Adds an Element to the element.
@param cite sets the cite="" attribute.
*/
public q(Element element, Element cite)
{
addElement(element);
setCite(cite);
}
/**
Basic constructor.
@param element Adds an Element to the element.
@param cite sets the cite="" attribute.
*/
public q(String element, Element cite)
{
addElement(element);
setCite(cite);
}
/**
Sets the cite="" attribute.
@param cite sets the cite="" attribute.
*/
public q setCite(String cite)
{
addAttribute("cite",cite);
return(this);
}
/**
Sets the cite="" attribute.
@param cite sets the cite="" attribute.
*/
public q setCite(Element cite)
{
addAttribute("cite",cite);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public q addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public q addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public q addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public q addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public q removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
/**
The onclick event occurs when the pointing device button is clicked
over an element. This attribute may be used with most elements.
@param The script
*/
public void setOnClick(String script)
{
addAttribute ( "onclick", script );
}
/**
The ondblclick event occurs when the pointing device button is double
clicked over an element. This attribute may be used with most elements.
@param The script
*/
public void setOnDblClick(String script)
{
addAttribute ( "ondblclick", script );
}
/**
The onmousedown event occurs when the pointing device button is pressed
over an element. This attribute may be used with most elements.
@param The script
*/
public void setOnMouseDown(String script)
{
addAttribute ( "onmousedown", script );
}
/**
The onmouseup event occurs when the pointing device button is released
over an element. This attribute may be used with most elements.
@param The script
*/
public void setOnMouseUp(String script)
{
addAttribute ( "onmouseup", script );
}
/**
The onmouseover event occurs when the pointing device is moved onto an
element. This attribute may be used with most elements.
@param The script
*/
public void setOnMouseOver(String script)
{
addAttribute ( "onmouseover", script );
}
/**
The onmousemove event occurs when the pointing device is moved while it
is over an element. This attribute may be used with most elements.
@param The script
*/
public void setOnMouseMove(String script)
{
addAttribute ( "onmousemove", script );
}
/**
The onmouseout event occurs when the pointing device is moved away from
an element. This attribute may be used with most elements.
@param The script
*/
public void setOnMouseOut(String script)
{
addAttribute ( "onmouseout", script );
}
/**
The onkeypress event occurs when a key is pressed and released over an
element. This attribute may be used with most elements.
@param The script
*/
public void setOnKeyPress(String script)
{
addAttribute ( "onkeypress", script );
}
/**
The onkeydown event occurs when a key is pressed down over an element.
This attribute may be used with most elements.
@param The script
*/
public void setOnKeyDown(String script)
{
addAttribute ( "onkeydown", script );
}
/**
The onkeyup event occurs when a key is released over an element. This
attribute may be used with most elements.
@param The script
*/
public void setOnKeyUp(String script)
{
addAttribute ( "onkeyup", script );
}
}
| erpcya/adempierePOS | tools/src/org/apache/ecs/xhtml/q.java | Java | gpl-2.0 | 9,368 |
/**
* Copyright (c) 2009--2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.taglibs.list.decorators;
import javax.servlet.jsp.JspException;
import org.apache.commons.lang.StringUtils;
import com.redhat.rhn.common.localization.LocalizationService;
import com.redhat.rhn.frontend.html.HtmlTag;
import com.redhat.rhn.frontend.taglibs.ListDisplayTag;
import com.redhat.rhn.frontend.taglibs.list.ListTagHelper;
import com.redhat.rhn.frontend.taglibs.list.ListTagUtil;
import com.redhat.rhn.frontend.taglibs.list.SelectableColumnTag;
import com.redhat.rhn.manager.rhnset.RhnSetDecl;
/**
* Handles selectable lists, such as lists backed by RhnSet
*
* @version $Rev $
*/
public class SelectableDecorator extends BaseListDecorator {
private static final String NULL_SELECTION = "0";
private static final String JAVASCRIPT_TAG =
"<script type=\"text/javascript\">%s</script>";
/**
* {@inheritDoc}
*/
@Override
public void beforeList() throws JspException {
ListTagUtil.write(pageContext, "<input type=\"hidden\" name=\"list_" +
listName + "_all\" value=\"false\" id=\"" + "list_" + listName +
"_all\" />");
ListTagUtil.write(pageContext, "<input type=\"hidden\" name=\"list_" +
listName + "_none\" value=\"false\" id=\"" + "list_" + listName +
"_none\" />");
}
/**
* {@inheritDoc}
*/
@Override
public void afterTopPagination() throws JspException {
renderSelectedCaption(true);
}
/**
* {@inheritDoc}
*/
@Override
public void afterBottomPagination() throws JspException {
renderSelectedCaption(false);
}
/**
* {@inheritDoc}
*/
@Override
public void onFooterExtraAddons() throws JspException {
renderSelectButtons();
}
/**
* {@inheritDoc}
*/
@Override
public void afterList() throws JspException {
String script = SelectableColumnTag.
getPostScript(listName, pageContext.getRequest());
if (!StringUtils.isBlank(script)) {
ListTagUtil.write(pageContext, String.format(JAVASCRIPT_TAG, script));
}
}
private void renderSelectedCaption(boolean isHeader) throws JspException {
if (!currentList.isEmpty()) {
String selectedName = ListTagUtil.makeSelectedAmountName(listName);
String selected = (String) pageContext.getRequest().getAttribute(selectedName);
if (selected == null) {
selected = NULL_SELECTION;
}
LocalizationService ls = LocalizationService.getInstance();
Object[] args = new Object[1];
args[0] = selected;
//
//
String setName = ListTagHelper.lookupSetDeclFor(listName,
pageContext.getRequest());
if (!RhnSetDecl.SYSTEMS.getLabel().equals(setName)) {
String msg = ls.getMessage("message.numselected", args);
ListTagUtil.write(pageContext, " <strong><span id=\"");
if (isHeader) {
ListTagUtil.write(pageContext, "pagination_selcount_top");
}
else {
ListTagUtil.write(pageContext, "pagination_selcount_bottom");
}
ListTagUtil.write(pageContext, "\">");
ListTagUtil.write(pageContext, msg);
ListTagUtil.write(pageContext, "</span></strong>");
}
}
}
private void renderSelectButtons() throws JspException {
if (!currentList.isEmpty()) {
StringBuilder buf = new StringBuilder();
buf.append("<span class=\"spacewalk-list-selection-btns\">");
String buttonName = ListTagUtil.makeSelectActionName(listName);
LocalizationService ls = LocalizationService.getInstance();
HtmlTag tag = new HtmlTag("button");
tag.setAttribute("class", "btn btn-default");
tag.setAttribute("type", "submit");
tag.setAttribute("name", buttonName);
tag.setAttribute("value",
ls.getMessage(ListDisplayTag.UPDATE_LIST_KEY));
tag.setAttribute("id", "update_list_key_id");
tag.setBody(ls.getMessage(ListDisplayTag.UPDATE_LIST_KEY));
buf.append(tag.render()).append(" ");
tag.setAttribute("value",
ls.getMessage(ListDisplayTag.SELECT_ALL_KEY));
tag.setBody(ls.getMessage(ListDisplayTag.SELECT_ALL_KEY));
buf.append(tag.render()).append(" ");
String selectedName = ListTagUtil.makeSelectedAmountName(listName);
String selected = (String) pageContext.getRequest().getAttribute(selectedName);
if (!NULL_SELECTION.equals(selected) && selected != null) {
tag.setAttribute("value",
ls.getMessage(ListDisplayTag.UNSELECT_ALL_KEY));
tag.setBody(ls.getMessage(ListDisplayTag.UNSELECT_ALL_KEY));
buf.append(tag.render()).append("\n");
}
buf.append("</span>");
ListTagUtil.write(pageContext, buf.toString());
}
}
}
| xkollar/spacewalk | java/code/src/com/redhat/rhn/frontend/taglibs/list/decorators/SelectableDecorator.java | Java | gpl-2.0 | 5,874 |
/*
*
*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This 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 for more details (a copy is
* included at /legal/license.txt).
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package java.lang;
/**
* Instances of the class <code>Class</code> represent classes and interfaces
* in a running Java application. Every array also belongs to a class that is
* reflected as a <code>Class</code> object that is shared by all arrays with
* the same element type and number of dimensions.
*
* <p> <code>Class</code> has no public constructor. Instead <code>Class</code>
* objects are constructed automatically by the Java Virtual Machine as classes
* are loaded.
*
* <p> The following example uses a <code>Class</code> object to print the
* class name of an object:
*
* <p> <blockquote><pre>
* void printClassName(Object obj) {
* System.out.println("The class of " + obj +
* " is " + obj.getClass().getName());
* }
* </pre></blockquote>
*
* @version 12/17/01 (CLDC 1.1)
* @since JDK1.0, CLDC 1.0
*/
public final
class Class {
/*
* Constructor. Only the Java Virtual Machine creates Class
* objects.
*/
private Class() {}
/**
* Converts the object to a string. The string representation is the
* string "class" or "interface", followed by a space, and then by the
* fully qualified name of the class in the format returned by
* <code>getName</code>. If this <code>Class</code> object represents a
* primitive type, this method returns the name of the primitive type. If
* this <code>Class</code> object represents void this method returns
* "void".
*
* @return a string representation of this class object.
*/
public String toString() {
return (isInterface() ? "interface " : "class ") + getName();
}
/**
* Returns the <code>Class</code> object associated with the class
* with the given string name. Given the fully-qualified name for
* a class or interface, this method attempts to locate, load and
* link the class.
* <p>
* For example, the following code fragment returns the runtime
* <code>Class</code> descriptor for the class named
* <code>java.lang.Thread</code>:
* <ul><code>
* Class t = Class.forName("java.lang.Thread")
* </code></ul>
*
* @param className the fully qualified name of the desired class.
* @return the <code>Class</code> object for the class with the
* specified name.
* @exception ClassNotFoundException if the class could not be found.
* @exception Error if the function fails for any other reason.
* @since JDK1.0
*/
public static native Class forName(String className)
throws ClassNotFoundException;
/**
* Creates a new instance of a class.
*
* @return a newly allocated instance of the class represented by this
* object. This is done exactly as if by a <code>new</code>
* expression with an empty argument list.
* @exception IllegalAccessException if the class or initializer is
* not accessible.
* @exception InstantiationException if an application tries to
* instantiate an abstract class or an interface, or if the
* instantiation fails for some other reason.
* @since JDK1.0
*/
public native Object newInstance()
throws InstantiationException, IllegalAccessException;
/**
* Determines if the specified <code>Object</code> is assignment-compatible
* with the object represented by this <code>Class</code>. This method is
* the dynamic equivalent of the Java language <code>instanceof</code>
* operator. The method returns <code>true</code> if the specified
* <code>Object</code> argument is non-null and can be cast to the
* reference type represented by this <code>Class</code> object without
* raising a <code>ClassCastException.</code> It returns <code>false</code>
* otherwise.
*
* <p> Specifically, if this <code>Class</code> object represents a
* declared class, this method returns <code>true</code> if the specified
* <code>Object</code> argument is an instance of the represented class (or
* of any of its subclasses); it returns <code>false</code> otherwise. If
* this <code>Class</code> object represents an array class, this method
* returns <code>true</code> if the specified <code>Object</code> argument
* can be converted to an object of the array class by an identity
* conversion or by a widening reference conversion; it returns
* <code>false</code> otherwise. If this <code>Class</code> object
* represents an interface, this method returns <code>true</code> if the
* class or any superclass of the specified <code>Object</code> argument
* implements this interface; it returns <code>false</code> otherwise. If
* this <code>Class</code> object represents a primitive type, this method
* returns <code>false</code>.
*
* @param obj the object to check
* @return true if <code>obj</code> is an instance of this class
*
* @since JDK1.1
*/
public native boolean isInstance(Object obj);
/**
* Determines if the class or interface represented by this
* <code>Class</code> object is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the specified
* <code>Class</code> parameter. It returns <code>true</code> if so;
* otherwise it returns <code>false</code>. If this <code>Class</code>
* object represents a primitive type, this method returns
* <code>true</code> if the specified <code>Class</code> parameter is
* exactly this <code>Class</code> object; otherwise it returns
* <code>false</code>.
*
* <p> Specifically, this method tests whether the type represented by the
* specified <code>Class</code> parameter can be converted to the type
* represented by this <code>Class</code> object via an identity conversion
* or via a widening reference conversion. See <em>The Java Language
* Specification</em>, sections 5.1.1 and 5.1.4 , for details.
*
* @param cls the <code>Class</code> object to be checked
* @return the <code>boolean</code> value indicating whether objects of the
* type <code>cls</code> can be assigned to objects of this class
* @exception NullPointerException if the specified Class parameter is
* null.
* @since JDK1.1
*/
public native boolean isAssignableFrom(Class cls);
/**
* Determines if the specified <code>Class</code> object represents an
* interface type.
*
* @return <code>true</code> if this object represents an interface;
* <code>false</code> otherwise.
*/
public native boolean isInterface();
/**
* Determines if this <code>Class</code> object represents an array class.
*
* @return <code>true</code> if this object represents an array class;
* <code>false</code> otherwise.
* @since JDK1.1
*/
public native boolean isArray();
/**
* Returns the fully-qualified name of the entity (class, interface, array
* class, primitive type, or void) represented by this <code>Class</code>
* object, as a <code>String</code>.
*
* <p> If this <code>Class</code> object represents a class of arrays, then
* the internal form of the name consists of the name of the element type
* in Java signature format, preceded by one or more "<tt>[</tt>"
* characters representing the depth of array nesting. Thus:
*
* <blockquote><pre>
* (new Object[3]).getClass().getName()
* </pre></blockquote>
*
* returns "<code>[Ljava.lang.Object;</code>" and:
*
* <blockquote><pre>
* (new int[3][4][5][6][7][8][9]).getClass().getName()
* </pre></blockquote>
*
* returns "<code>[[[[[[[I</code>". The encoding of element type names
* is as follows:
*
* <blockquote><pre>
* B byte
* C char
* D double
* F float
* I int
* J long
* L<i>classname;</i> class or interface
* S short
* Z boolean
* </pre></blockquote>
*
* The class or interface name <tt><i>classname</i></tt> is given in fully
* qualified form as shown in the example above.
*
* @return the fully qualified name of the class or interface
* represented by this object.
*/
public native String getName();
/**
* Finds a resource with a given name in the application's
* JAR file. This method returns
* <code>null</code> if no resource with this name is found
* in the application's JAR file.
* <p>
* The resource names can be represented in two
* different formats: absolute or relative.
* <p>
* Absolute format:
* <ul><code>/packagePathName/resourceName</code></ul>
* <p>
* Relative format:
* <ul><code>resourceName</code></ul>
* <p>
* In the absolute format, the programmer provides a fully
* qualified name that includes both the full path and the
* name of the resource inside the JAR file. In the path names,
* the character "/" is used as the separator.
* <p>
* In the relative format, the programmer provides only
* the name of the actual resource. Relative names are
* converted to absolute names by the system by prepending
* the resource name with the fully qualified package name
* of class upon which the <code>getResourceAsStream</code>
* method was called.
*
* @param name name of the desired resource
* @return a <code>java.io.InputStream</code> object.
*/
public java.io.InputStream getResourceAsStream(String name) {
try {
if (name.length() > 0 && name.charAt(0) == '/') {
/* Absolute format */
name = name.substring(1);
} else {
/* Relative format */
String className = this.getName();
int dotIndex = className.lastIndexOf('.');
if (dotIndex >= 0) {
name = className.substring(0, dotIndex + 1).replace('.', '/')
+ name;
}
}
return new com.sun.cldc.io.ResourceInputStream(name);
} catch (java.io.IOException x) {
return null;
}
}
/*
* This private function is used during virtual machine initialization.
* The user does not normally see this function.
*/
// private static void runCustomCode() {}
/* The code below is specific to this VM */
/**
* Returns the <code>Class</code> representing the superclass of the entity
* (class, interface, primitive type or void) represented by this
* <code>Class</code>. If this <code>Class</code> represents either the
* <code>Object</code> class, an interface, a primitive type, or void, then
* null is returned. If this object represents an array class then the
* <code>Class</code> object representing the <code>Object</code> class is
* returned.
*
* Note that this method is not supported by CLDC.
* We have made the method private, since it is
* needed by our implementation.
*
* @return the superclass of the class represented by this object.
*/
private native Class getSuperclass();
/*
* This private variable is used by the VM.
* Users never see it.
*/
private transient Object vmClass;
private int status;
private Thread thread;
private static final int IN_PROGRESS = 1;
private static final int VERIFIED = 2;
private static final int INITIALIZED = 4;
private static final int ERROR = 8;
// Native for invoking <clinit>
private native void invoke_clinit();
/**
* Initialization at step 9:
* If ENABLE_ISOLATES == false
* Remove the <clinit> method after the class is initialized.
* If ENABLE_ISOLATES == true, clear class initialization
* barrier.
*/
private native void init9();
private native void invoke_verify();
/*
* Implements the 11 step program detailed in Java Language Specification
* 12.4.2
*/
void initialize() throws Throwable {
// Step 1
synchronized (this) {
// Step 2
while ((status & IN_PROGRESS) != 0 && thread != Thread.currentThread()) {
try{
wait();
} catch (InterruptedException e) {
}
}
// Step 3
if ((status & IN_PROGRESS) != 0 && thread == Thread.currentThread()) {
return;
}
// Step 4
if ((status & INITIALIZED) != 0) {
return;
}
// Step 5
if (status == ERROR) {
throw new NoClassDefFoundError(getName());
}
/* Note: CLDC 1.0 does not have NoClassDefFoundError class */
// Step 6
status |= IN_PROGRESS;
thread = Thread.currentThread();
}
try {
// Step 7
invoke_verify();
Class s = getSuperclass();
if (s != null && (s.status & INITIALIZED) == 0) {
// The test of s.status is not part of the spec, but
// it saves us doing a lot of work in the most common
// case.
s.initialize();
}
// Step 8
invoke_clinit();
// Step 9
synchronized (this) {
status &= ~IN_PROGRESS;
status |= INITIALIZED;
thread = null;
init9();
notifyAll();
}
} catch(Throwable e) {
// Step 10 and 11
// CR 6224346, The cldc_vm threading mechanism is such that
// we can just jam these values in without fear of another
// thread doing the same since only this thread can be
// executing the initialize() method and the scheduler is
// non-preemptive. We do this here in case the monitorenter
// fails due to OOME because some other thread holds the lock,
// memory is low and we need to allocate a ConditionDesc to
// wait for the lock.
status = ERROR;
thread = null;
synchronized (this) {
notifyAll();
throwError(e);
}
}
}
private Error throwError(Throwable e) throws Error {
throw (e instanceof Error) ? (Error)e
: new Error("Static initializer: " + e.getClass().getName() +
", " + e.getMessage());
}
}
| sics-sse/moped | squawk/phoneme/cldc/src/javaapi/cldc1.1/java/lang/Class.java | Java | gpl-2.0 | 16,089 |
package com.engc.smartedu.ui.userinfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.engc.smartedu.R;
/**
* User: qii
* Date: 12-12-9
*/
public class UserAvatarDialog extends DialogFragment {
private String path;
public UserAvatarDialog() {
}
public UserAvatarDialog(String path) {
this.path = path;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("path", path);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
path = savedInstanceState.getString("path");
}
Bitmap bitmap = BitmapFactory.decodeFile(path);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.UserAvatarDialog);
View customView = getActivity().getLayoutInflater().inflate(R.layout.useravatardialog_layout, null);
((ImageView) customView.findViewById(R.id.imageview)).setImageBitmap(bitmap);
builder.setView(customView);
return builder.create();
}
}
| rabbpigPan/smartedu | src/com/engc/smartedu/ui/userinfo/UserAvatarDialog.java | Java | gpl-3.0 | 1,339 |
/**
* 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 com.datatorrent.lib.appdata.datastructs;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* This is a {@link DimensionalTable}. A {@link DimensionalTable} is similar to a Map but is a hybrid
* between a conventional table and a map. Data in a {@link DimensionalTable} is organized into rows
* and each row is broken into two parts, the key and the data payload. Each key is composed of a predefined list
* of fields. A Diagram is below:
* <br/>
* <br/>
* <table border="1">
* <tr>
* <td></td>
* <td>Key</td>
* <td>Value</td>
* </tr>
* <tr>
* <td></td>
* <td>
* <table border="1">
* <tr>
* <td>Header 1</td>
* <td>Header 2</td>
* <td>Header 3</td>
* <td>...</td>
* </tr>
* </table>
* </td>
* <td></td>
* </tr>
* <tr>
* <td>
* Row 1
* </td>
* <td>
* <table border="1">
* <tr>
* <td>field 1 </td>
* <td>field 2 </td>
* <td>field 3 </td>
* <td>...</td>
* </tr>
* </table>
* </td>
* <td>Data payload</td>
* </tr>
* </table>
* <br/>
* <br/>
* The purpose of this table is to provide a <b>select-like</b> feature for obtaining data payloads.
* Selecting works as follows. If a user specifies one or more key components in a search query, but not
* all the key components, then all the data payloads with a matching subset of key components are returned. If
* all the key components are specified in a search query, then only a single data payload is returned if there
* is a matching key, otherwise nothing is returned.
*
* @param <DATA> The type of the data payload.
* @since 3.0.0
*/
public class DimensionalTable<DATA>
{
private static final Logger logger = LoggerFactory.getLogger(DimensionalTable.class);
/**
* This is a map from the header name to its column index.
*/
protected final Map<String, Integer> dimensionNameToIndex = Maps.newHashMap();
/**
* This is a column which holds the data payload.
*/
protected final List<DATA> dataColumn = Lists.newArrayList();
/**
* These are the columns which hold each component of the key.
*/
protected final List<List<Object>> dimensionColumns = Lists.newArrayList();
/**
* A map from a key row to its data payload.
*/
protected final Map<List<Object>, DATA> dimensionKeysToData = Maps.newHashMap();
/**
* Constructor for Kryo
*/
private DimensionalTable()
{
//For Kryo
}
/**
* Creates a dimensional table with the given header names for key columns.
* @param headerNames The header names for key columns.
*/
public DimensionalTable(List<String> headerNames)
{
setHeaderNames(headerNames);
initialize();
}
/**
* Initializing the key element columns.
*/
private void initialize()
{
for (int columnIndex = 0; columnIndex < dimensionNameToIndex.size(); columnIndex++) {
dimensionColumns.add(Lists.newArrayList());
}
}
/**
* Helper method to set and validate the header names for the table.
* @param headerNames The head names for the key components of the table.
*/
private void setHeaderNames(List<String> headerNames)
{
Preconditions.checkNotNull(headerNames);
Preconditions.checkArgument(!headerNames.isEmpty(), "headerNames");
for (String headerName : headerNames) {
Preconditions.checkNotNull(headerName);
}
Set<String> headerNameSet = Sets.newHashSet(headerNames);
Preconditions.checkArgument(headerNameSet.size() == headerNames.size(),
"The provided list of header names has duplicate names: " + headerNames);
for (int index = 0; index < headerNames.size(); index++) {
dimensionNameToIndex.put(headerNames.get(index), index);
}
}
/**
* Appends a row to the table. If the key combination for the row is not unique
* then the existing row is replaced.
* @param data The data payload for the row.
* @param keys The values for the components of the keys. The key components
* must be specified in the same order as their header names.
*/
public void appendRow(DATA data, Object... keys)
{
Preconditions.checkNotNull(data);
Preconditions.checkNotNull(keys);
Preconditions.checkArgument(keys.length == dimensionNameToIndex.size(),
"All the dimension keys should be specified.");
List<Object> keysList = Lists.newArrayList();
for (Object key : keys) {
keysList.add(key);
}
DATA prev = dimensionKeysToData.put(keysList, data);
if (prev != null) {
return;
}
dataColumn.add(data);
for (int index = 0; index < keys.length; index++) {
Object key = keys[index];
dimensionColumns.get(index).add(key);
}
}
/**
* Appends a row to the table.
* @param data The data payload for the row.
* @param keys The values for the key components of the row. The key of the provided map corresponds to the
* header name of a key component, and the value of the provided map corresponds to the value of a key component.
*/
public void appendRow(DATA data, Map<String, ?> keys)
{
Preconditions.checkNotNull(data);
Preconditions.checkNotNull(keys);
Object[] keysArray = new Object[keys.size()];
for (Map.Entry<String, ?> entry : keys.entrySet()) {
String keyName = entry.getKey();
Object value = entry.getValue();
Preconditions.checkNotNull(keyName);
Integer index = dimensionNameToIndex.get(keyName);
keysArray[index] = value;
}
appendRow(data, keysArray);
}
/**
* This method returns a data payload corresponding to the provided key, or null if there is no data payload
* corresponding to the provided key.
* @param keys A list containing the values of all the components of the key. The values of the key
* components must be provided in the same order as their header names.
* @return The data payload corresponding to the given key.
*/
@SuppressWarnings("element-type-mismatch")
public DATA getDataPoint(List<?> keys)
{
Preconditions.checkNotNull(keys);
Preconditions.checkArgument(keys.size() == dimensionNameToIndex.size(), "All the keys must be specified.");
return dimensionKeysToData.get(keys);
}
/**
* This method returns a data payload corresponding to the provided key, or null if there is no data payload
* corresponding to the provided key.
* @param keys The values for the key components of the row. The key of the provided map corresponds to the
* header name of a key component, and the value of the provided map corresponds to the value of a key component.
* @return The data payload corresponding to the given key.
*/
public DATA getDataPoint(Map<String, ?> keys)
{
Preconditions.checkNotNull(keys);
Preconditions.checkArgument(keys.size() == dimensionNameToIndex.size(), "All the keys must be specified.");
List<Object> keysList = Lists.newArrayList();
for (int index = 0; index < dimensionNameToIndex.size(); index++) {
keysList.add(null);
}
for (Map.Entry<String, ?> entry : keys.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Integer index = dimensionNameToIndex.get(key);
keysList.set(index, value);
}
return getDataPoint(keysList);
}
/**
* This method returns all the data payloads which correspond with the given subset of key components.
* @param keys The values for the key components of the row. The key of the provided map corresponds to the
* header name of a key component, and the value of the provided map corresponds to the value of a key component.
* @return The data payloads corresponding to the given subset of key components.
*/
public List<DATA> getDataPoints(Map<String, ?> keys)
{
Preconditions.checkNotNull(keys);
Preconditions.checkArgument(dimensionNameToIndex.keySet().containsAll(keys.keySet()),
"The given keys contain names which are not valid keys.");
List<Integer> indices = Lists.newArrayList();
List<List<Object>> keyColumns = Lists.newArrayList();
Map<Integer, Object> indexToKey = Maps.newHashMap();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
String dimensionName = entry.getKey();
Object value = entry.getValue();
Integer index = dimensionNameToIndex.get(dimensionName);
indices.add(index);
indexToKey.put(index, value);
}
Collections.sort(indices);
List<Object> tempKeys = Lists.newArrayList();
for (Integer index : indices) {
tempKeys.add(indexToKey.get(index));
keyColumns.add(dimensionColumns.get(index));
}
int numRows = keyColumns.get(0).size();
List<DATA> results = Lists.newArrayList();
for (int rowIndex = 0; rowIndex < numRows; rowIndex++) {
boolean allEqual = true;
for (int columnIndex = 0; columnIndex < tempKeys.size(); columnIndex++) {
Object key = tempKeys.get(columnIndex);
Object keyColumn = keyColumns.get(columnIndex).get(rowIndex);
if ((key == null && keyColumn != null) ||
(key != null && keyColumn == null) ||
(key != null && !keyColumn.equals(key))) {
allEqual = false;
break;
}
}
if (allEqual) {
results.add(dataColumn.get(rowIndex));
}
}
return results;
}
/**
* Returns all the data payloads in the table.
* @return The data payload column of the table.
*/
public List<DATA> getAllDataPoints()
{
return Lists.newArrayList(dataColumn);
}
/**
* Returns the number of rows in the table.
* @return The number of rows in the table.
*/
public int size()
{
return dataColumn.size();
}
}
| PramodSSImmaneni/apex-malhar | library/src/main/java/com/datatorrent/lib/appdata/datastructs/DimensionalTable.java | Java | apache-2.0 | 10,943 |
/*
* 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 org.jetbrains.idea.maven.dom;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import java.util.List;
public class MavenPropertyFindUsagesTest extends MavenDomTestCase {
@Override
protected void setUpInWriteAction() throws Exception {
super.setUpInWriteAction();
importProject("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>1</version>");
}
public void testFindModelPropertyFromReference() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>1</version>" +
"<name>${<caret>project.version}</name>" +
"<description>${project.version}</description>");
assertSearchResults(myProjectPom,
findTag("project.name"),
findTag("project.description"));
}
public void testFindModelPropertyFromReferenceWithDifferentQualifiers() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>1</version>" +
"<name>${<caret>version}</name>" +
"<description>${pom.version}</description>");
assertSearchResults(myProjectPom,
findTag("project.name"),
findTag("project.description"));
}
public void testFindUsagesFromTag() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<<caret>version>1</version>" +
"<name>${project.version}</name>" +
"<description>${version}</description>");
assertSearchResults(myProjectPom,
findTag("project.name"),
findTag("project.description"));
}
public void testFindUsagesFromTagValue() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>1<caret>1</version>" +
"<name>${project.version}</name>");
assertSearchResults(myProjectPom, findTag("project.name"));
}
public void testFindUsagesFromProperty() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>11</version>" +
"<name>${foo}</name>" +
"<properties>" +
" <f<caret>oo>value</foo>" +
"</properties>");
assertSearchResultsInclude(myProjectPom, findTag("project.name"));
}
public void testFindUsagesForEnvProperty() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>11</version>" +
"<name>${env.<caret>" + getEnvVar() + "}</name>" +
"<description>${env." + getEnvVar() + "}</description>");
assertSearchResultsInclude(myProjectPom, findTag("project.name"), findTag("project.description"));
}
public void testFindUsagesForSystemProperty() throws Exception {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<version>11</version>" +
"<name>${use<caret>r.home}</name>" +
"<description>${user.home}</description>");
assertSearchResultsInclude(myProjectPom, findTag("project.name"), findTag("project.description"));
}
public void testFindUsagesForSystemPropertyInFilteredResources() throws Exception {
createProjectSubDir("res");
importProject("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>" +
"<name>${user.home}</name>" +
"<build>" +
" <resources>" +
" <resource>" +
" <directory>res</directory>" +
" <filtering>true</filtering>" +
" </resource>" +
" </resources>" +
"</build>");
VirtualFile f = createProjectSubFile("res/foo.properties",
"foo=abc${user<caret>.home}abc");
List<PsiElement> result = search(f);
assertContain(result, findTag("project.name"), MavenDomUtil.findPropertyValue(myProject, f, "foo"));
}
public void testHighlightingFromTag() {
createProjectPom("<groupId>test</groupId>" +
"<artifactId>module1</artifactId>" +
"<<caret>version>1</version>" +
"<name>${project.version}</name>" +
"<description>${version}</description>");
assertHighlighted(myProjectPom,
new HighlightInfo(findTag("project.name"), "project.version"),
new HighlightInfo(findTag("project.description"), "version"));
}
}
| dahlstrom-g/intellij-community | plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPropertyFindUsagesTest.java | Java | apache-2.0 | 5,789 |
/*
* 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.drools.compiler.compiler;
import org.drools.compiler.lang.descr.BaseDescr;
public class ActionError extends DroolsError {
private BaseDescr descr;
private Object object;
private String message;
private int[] errorLines = new int[0];
public ActionError(final BaseDescr descr,
final Object object,
final String message) {
this.descr = descr;
this.object = object;
this.message = message;
}
@Override
public String getNamespace() {
return descr.getNamespace();
}
public BaseDescr getDescr() {
return this.descr;
}
public Object getObject() {
return this.object;
}
public int[] getLines() {
return this.errorLines;
}
/**
* This will return the line number of the error, if possible
* Otherwise it will be -1
*/
public int getLine() {
return this.descr != null ? this.descr.getLine() : -1;
}
public String getMessage() {
return BuilderResultUtils.getProblemMessage( this.object, this.message, "\n" );
}
public String toString() {
final StringBuilder builder = new StringBuilder()
.append( this.message )
.append( " : " )
.append( "\n" );
return BuilderResultUtils.appendProblems( this.object, builder ).toString();
}
}
| droolsjbpm/drools | drools-compiler/src/main/java/org/drools/compiler/compiler/ActionError.java | Java | apache-2.0 | 2,050 |
package com.salesmanager.core.business.system.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.Type;
import com.salesmanager.core.business.common.model.audit.AuditListener;
import com.salesmanager.core.business.common.model.audit.AuditSection;
import com.salesmanager.core.business.common.model.audit.Auditable;
import com.salesmanager.core.business.generic.model.SalesManagerEntity;
import com.salesmanager.core.business.merchant.model.MerchantStore;
import com.salesmanager.core.constants.SchemaConstant;
/**
* Merchant configuration information
* @author Carl Samson
*
*/
@Entity
@EntityListeners(value = AuditListener.class)
@Table(name = "MERCHANT_CONFIGURATION", schema= SchemaConstant.SALESMANAGER_SCHEMA, uniqueConstraints=
@UniqueConstraint(columnNames = {"MERCHANT_ID", "CONFIG_KEY"}))
public class MerchantConfiguration extends SalesManagerEntity<Long, MerchantConfiguration> implements Serializable, Auditable {
/**
*
*/
private static final long serialVersionUID = 4246917986731953459L;
@Id
@Column(name = "MERCHANT_CONFIG_ID")
@TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "MERCH_CONF_SEQ_NEXT_VAL")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="MERCHANT_ID", nullable=true)
private MerchantStore merchantStore;
@Embedded
private AuditSection auditSection = new AuditSection();
@Column(name="CONFIG_KEY")
private String key;
@Column(name="VALUE")
@Type(type = "org.hibernate.type.StringClobType")
private String value;
@Column(name="TYPE")
@Enumerated(value = EnumType.STRING)
private MerchantConfigurationType merchantConfigurationType = MerchantConfigurationType.INTEGRATION;
public void setKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public AuditSection getAuditSection() {
return auditSection;
}
public void setAuditSection(AuditSection auditSection) {
this.auditSection = auditSection;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public MerchantStore getMerchantStore() {
return merchantStore;
}
public void setMerchantStore(MerchantStore merchantStore) {
this.merchantStore = merchantStore;
}
public void setMerchantConfigurationType(MerchantConfigurationType merchantConfigurationType) {
this.merchantConfigurationType = merchantConfigurationType;
}
public MerchantConfigurationType getMerchantConfigurationType() {
return merchantConfigurationType;
}
}
| asheshsaraf/ecommerce-simple | sm-core/src/main/java/com/salesmanager/core/business/system/model/MerchantConfiguration.java | Java | apache-2.0 | 3,336 |
package com.example.android.lifecycle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/*
* This tag will be used for logging. It is best practice to use the class's name using
* getSimpleName as that will greatly help to identify the location from which your logs are
* being posted.
*/
private static final String TAG = MainActivity.class.getSimpleName();
/*
* This constant String will be used to store the content of the TextView used to display the
* list of callbacks. The reason we are storing the contents of the TextView is so that you can
* see the entire set of callbacks as they are called.
*/
private static final String LIFECYCLE_CALLBACKS_TEXT_KEY = "callbacks";
/* Constant values for the names of each respective lifecycle callback */
private static final String ON_CREATE = "onCreate";
private static final String ON_START = "onStart";
private static final String ON_RESUME = "onResume";
private static final String ON_PAUSE = "onPause";
private static final String ON_STOP = "onStop";
private static final String ON_RESTART = "onRestart";
private static final String ON_DESTROY = "onDestroy";
private static final String ON_SAVE_INSTANCE_STATE = "onSaveInstanceState";
/*
* This TextView will contain a running log of every lifecycle callback method called from this
* Activity. This TextView can be reset to its default state by clicking the Button labeled
* "Reset Log"
*/
private TextView mLifecycleDisplay;
// TODO (1) Declare and instantiate a static ArrayList of Strings called mLifecycleCallbacks
/**
* Called when the activity is first created. This is where you should do all of your normal
* static set up: create views, bind data to lists, etc.
*
* Always followed by onStart().
*
* @param savedInstanceState The Activity's previously frozen state, if there was one.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLifecycleDisplay = (TextView) findViewById(R.id.tv_lifecycle_events_display);
/*
* If savedInstanceState is not null, that means our Activity is not being started for the
* first time. Even if the savedInstanceState is not null, it is smart to check if the
* bundle contains the key we are looking for. In our case, the key we are looking for maps
* to the contents of the TextView that displays our list of callbacks. If the bundle
* contains that key, we set the contents of the TextView accordingly.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(LIFECYCLE_CALLBACKS_TEXT_KEY)) {
String allPreviousLifecycleCallbacks = savedInstanceState
.getString(LIFECYCLE_CALLBACKS_TEXT_KEY);
mLifecycleDisplay.setText(allPreviousLifecycleCallbacks);
}
}
// TODO (4) Iterate backwards through mLifecycleCallbacks, appending each String and a newline to mLifecycleDisplay
// TODO (5) Clear mLifecycleCallbacks after iterating through it
logAndAppend(ON_CREATE);
}
/**
* Called when the activity is becoming visible to the user.
*
* Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes
* hidden.
*/
@Override
protected void onStart() {
super.onStart();
logAndAppend(ON_START);
}
/**
* Called when the activity will start interacting with the user. At this point your activity
* is at the top of the activity stack, with user input going to it.
*
* Always followed by onPause().
*/
@Override
protected void onResume() {
super.onResume();
logAndAppend(ON_RESUME);
}
/**
* Called when the system is about to start resuming a previous activity. This is typically
* used to commit unsaved changes to persistent data, stop animations and other things that may
* be consuming CPU, etc. Implementations of this method must be very quick because the next
* activity will not be resumed until this method returns.
*
* Followed by either onResume() if the activity returns back to the front, or onStop() if it
* becomes invisible to the user.
*/
@Override
protected void onPause() {
super.onPause();
logAndAppend(ON_PAUSE);
}
/**
* Called when the activity is no longer visible to the user, because another activity has been
* resumed and is covering this one. This may happen either because a new activity is being
* started, an existing one is being brought in front of this one, or this one is being
* destroyed.
*
* Followed by either onRestart() if this activity is coming back to interact with the user, or
* onDestroy() if this activity is going away.
*/
@Override
protected void onStop() {
super.onStop();
// TODO (2) Add the ON_STOP String to the front of mLifecycleCallbacks
logAndAppend(ON_STOP);
}
/**
* Called after your activity has been stopped, prior to it being started again.
*
* Always followed by onStart()
*/
@Override
protected void onRestart() {
super.onRestart();
logAndAppend(ON_RESTART);
}
/**
* The final call you receive before your activity is destroyed. This can happen either because
* the activity is finishing (someone called finish() on it, or because the system is
* temporarily destroying this instance of the activity to save space. You can distinguish
* between these two scenarios with the isFinishing() method.
*/
@Override
protected void onDestroy() {
super.onDestroy();
// TODO (3) Add the ON_DESTROY String to the front of mLifecycleCallbacks
logAndAppend(ON_DESTROY);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
logAndAppend(ON_SAVE_INSTANCE_STATE);
String lifecycleDisplayTextViewContents = mLifecycleDisplay.getText().toString();
outState.putString(LIFECYCLE_CALLBACKS_TEXT_KEY, lifecycleDisplayTextViewContents);
}
/**
* Logs to the console and appends the lifecycle method name to the TextView so that you can
* view the series of method callbacks that are called both from the app and from within
* Android Studio's Logcat.
*
* @param lifecycleEvent The name of the event to be logged.
*/
private void logAndAppend(String lifecycleEvent) {
Log.d(TAG, "Lifecycle Event: " + lifecycleEvent);
mLifecycleDisplay.append(lifecycleEvent + "\n");
}
/**
* This method resets the contents of the TextView to its default text of "Lifecycle callbacks"
*
* @param view The View that was clicked. In this case, it is the Button from our layout.
*/
public void resetLifecycleDisplay(View view) {
mLifecycleDisplay.setText("Lifecycle callbacks:\n");
}
}
| DhurimKelmendi/ud851-Exercises | Lesson05a-Android-Lifecycle/T05a.03-Exercise-FixLifecycleDisplayBug/app/src/main/java/com/example/android/lifecycle/MainActivity.java | Java | apache-2.0 | 7,430 |
/*
* 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.parquet.thrift.struct;
import static org.apache.parquet.thrift.struct.ThriftTypeID.BOOL;
import static org.apache.parquet.thrift.struct.ThriftTypeID.BYTE;
import static org.apache.parquet.thrift.struct.ThriftTypeID.DOUBLE;
import static org.apache.parquet.thrift.struct.ThriftTypeID.ENUM;
import static org.apache.parquet.thrift.struct.ThriftTypeID.I16;
import static org.apache.parquet.thrift.struct.ThriftTypeID.I32;
import static org.apache.parquet.thrift.struct.ThriftTypeID.I64;
import static org.apache.parquet.thrift.struct.ThriftTypeID.LIST;
import static org.apache.parquet.thrift.struct.ThriftTypeID.MAP;
import static org.apache.parquet.thrift.struct.ThriftTypeID.SET;
import static org.apache.parquet.thrift.struct.ThriftTypeID.STRING;
import static org.apache.parquet.thrift.struct.ThriftTypeID.STRUCT;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.annotate.JsonTypeInfo.As;
import org.codehaus.jackson.annotate.JsonTypeInfo.Id;
/**
* Descriptor for a Thrift class.
* Used to persist the thrift schema
*
* @author Julien Le Dem
*
*/
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "id")
@JsonSubTypes({
@JsonSubTypes.Type(value=ThriftType.BoolType.class, name="BOOL"),
@JsonSubTypes.Type(value=ThriftType.ByteType.class, name="BYTE"),
@JsonSubTypes.Type(value=ThriftType.DoubleType.class, name="DOUBLE"),
@JsonSubTypes.Type(value=ThriftType.EnumType.class, name="ENUM"),
@JsonSubTypes.Type(value=ThriftType.I16Type.class, name="I16"),
@JsonSubTypes.Type(value=ThriftType.I32Type.class, name="I32"),
@JsonSubTypes.Type(value=ThriftType.I64Type.class, name="I64"),
@JsonSubTypes.Type(value=ThriftType.ListType.class, name="LIST"),
@JsonSubTypes.Type(value=ThriftType.MapType.class, name="MAP"),
@JsonSubTypes.Type(value=ThriftType.SetType.class, name="SET"),
@JsonSubTypes.Type(value=ThriftType.StringType.class, name="STRING"),
@JsonSubTypes.Type(value=ThriftType.StructType.class, name="STRUCT")
})
public abstract class ThriftType {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ThriftType)) return false;
ThriftType that = (ThriftType) o;
if (type != that.type) return false;
return true;
}
@Override
public int hashCode() {
return type != null ? type.hashCode() : 0;
}
public static ThriftType fromJSON(String json) {
return JSON.fromJSON(json, ThriftType.class);
}
public String toJSON() {
return JSON.toJSON(this);
}
@Override
public String toString() {
return toJSON();
}
public interface StateVisitor<R, S> {
R visit(MapType mapType, S state);
R visit(SetType setType, S state);
R visit(ListType listType, S state);
R visit(StructType structType, S state);
R visit(EnumType enumType, S state);
R visit(BoolType boolType, S state);
R visit(ByteType byteType, S state);
R visit(DoubleType doubleType, S state);
R visit(I16Type i16Type, S state);
R visit(I32Type i32Type, S state);
R visit(I64Type i64Type, S state);
R visit(StringType stringType, S state);
}
/**
* @deprecated will be removed in 2.0.0; use StateVisitor instead.
*/
public interface TypeVisitor {
void visit(MapType mapType);
void visit(SetType setType);
void visit(ListType listType);
void visit(StructType structType);
void visit(EnumType enumType);
void visit(BoolType boolType);
void visit(ByteType byteType);
void visit(DoubleType doubleType);
void visit(I16Type i16Type);
void visit(I32Type i32Type);
void visit(I64Type i64Type);
void visit(StringType stringType);
}
/**
* @deprecated will be removed in 2.0.0.
*/
@Deprecated
public static abstract class ComplexTypeVisitor implements TypeVisitor {
@Override
final public void visit(EnumType enumType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(BoolType boolType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(ByteType byteType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(DoubleType doubleType) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(I16Type i16Type) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(I32Type i32Type) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(I64Type i64Type) {
throw new IllegalArgumentException("Expected complex type");
}
@Override
final public void visit(StringType stringType) {
throw new IllegalArgumentException("Expected complex type");
}
}
public static class StructType extends ThriftType {
private final List<ThriftField> children;
private final ThriftField[] childById;
/**
* Whether a struct is a union or a regular struct is not always known, because it was not always
* written to the metadata files.
*
* We should always know this in the write path, but may not in the read path.
*/
public enum StructOrUnionType {
STRUCT,
UNION,
UNKNOWN
}
private final StructOrUnionType structOrUnionType;
@Deprecated
public StructType(List<ThriftField> children) {
this(children, null);
}
@JsonCreator
public StructType(@JsonProperty("children") List<ThriftField> children,
@JsonProperty("structOrUnionType") StructOrUnionType structOrUnionType) {
super(STRUCT);
this.structOrUnionType = structOrUnionType == null ? StructOrUnionType.UNKNOWN : structOrUnionType;
this.children = children;
int maxId = 0;
if (children != null) {
for (ThriftField thriftField : children) {
maxId = Math.max(maxId, thriftField.getFieldId());
}
childById = new ThriftField[maxId + 1];
for (ThriftField thriftField : children) {
childById[thriftField.getFieldId()] = thriftField;
}
} else {
childById = null;
}
}
public List<ThriftField> getChildren() {
return children;
}
@JsonIgnore
public ThriftField getChildById(short id) {
if (id >= childById.length) {
return null;
} else {
return childById[id];
}
}
@JsonProperty("structOrUnionType")
public StructOrUnionType getStructOrUnionType() {
return structOrUnionType;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StructType that = (StructType) o;
if (!Arrays.equals(childById, that.childById)) return false;
return true;
}
@Override
public int hashCode() {
int result = childById != null ? Arrays.hashCode(childById) : 0;
return result;
}
}
public static class MapType extends ThriftType {
private final ThriftField key;
private final ThriftField value;
@JsonCreator
public MapType(@JsonProperty("key") ThriftField key, @JsonProperty("value") ThriftField value) {
super(MAP);
this.key = key;
this.value = value;
}
public ThriftField getKey() {
return key;
}
public ThriftField getValue() {
return value;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MapType)) return false;
if (!super.equals(o)) return false;
MapType mapType = (MapType) o;
if (!key.equals(mapType.key)) return false;
if (!value.equals(mapType.value)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + key.hashCode();
result = 31 * result + value.hashCode();
return result;
}
}
public static class SetType extends ThriftType {
private final ThriftField values;
@JsonCreator
public SetType(@JsonProperty("values") ThriftField values) {
super(SET);
this.values = values;
}
public ThriftField getValues() {
return values;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SetType)) return false;
if (!super.equals(o)) return false;
SetType setType = (SetType) o;
if (!values.equals(setType.values)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + values.hashCode();
return result;
}
}
public static class ListType extends ThriftType {
private final ThriftField values;
@JsonCreator
public ListType(@JsonProperty("values") ThriftField values) {
super(LIST);
this.values = values;
}
public ThriftField getValues() {
return values;
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ListType)) return false;
if (!super.equals(o)) return false;
ListType listType = (ListType) o;
if (!values.equals(listType.values)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + values.hashCode();
return result;
}
}
public static class EnumValue {
private final int id;
private final String name;
@JsonCreator
public EnumValue(@JsonProperty("id") int id, @JsonProperty("name") String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnumValue)) return false;
EnumValue enumValue = (EnumValue) o;
if (id != enumValue.id) return false;
if (name != null ? !name.equals(enumValue.name) : enumValue.name != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
public static class EnumType extends ThriftType {
private final List<EnumValue> values;
private Map<Integer,EnumValue> idEnumLookup;
@JsonCreator
public EnumType(@JsonProperty("values") List<EnumValue> values) {
super(ENUM);
this.values = values;
}
public Iterable<EnumValue> getValues() {
return new Iterable<EnumValue>() {
@Override
public Iterator<EnumValue> iterator() {
return values.iterator();
}
};
}
public EnumValue getEnumValueById(int id) {
prepareEnumLookUp();
return idEnumLookup.get(id);
}
private void prepareEnumLookUp() {
if (idEnumLookup == null) {
idEnumLookup=new HashMap<Integer, EnumValue>();
for (EnumValue value : values) {
idEnumLookup.put(value.getId(),value);
}
}
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EnumType)) return false;
if (!super.equals(o)) return false;
EnumType enumType = (EnumType) o;
if (!values.equals(enumType.values)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + values.hashCode();
return result;
}
}
public static class BoolType extends ThriftType {
@JsonCreator
public BoolType() {
super(BOOL);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class ByteType extends ThriftType {
@JsonCreator
public ByteType() {
super(BYTE);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class DoubleType extends ThriftType {
@JsonCreator
public DoubleType() {
super(DOUBLE);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class I16Type extends ThriftType {
@JsonCreator
public I16Type() {
super(I16);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class I32Type extends ThriftType {
@JsonCreator
public I32Type() {
super(I32);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class I64Type extends ThriftType {
@JsonCreator
public I64Type() {
super(I64);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
public static class StringType extends ThriftType {
@JsonCreator
public StringType() {
super(STRING);
}
@Override
public <R, S> R accept(StateVisitor<R, S> visitor, S state) {
return visitor.visit(this, state);
}
@Override
public void accept(TypeVisitor visitor) {
visitor.visit(this);
}
}
private final ThriftTypeID type;
private ThriftType(ThriftTypeID type) {
super();
this.type = type;
}
public abstract void accept(TypeVisitor visitor);
public abstract <R, S> R accept(StateVisitor<R, S> visitor, S state);
@JsonIgnore
public ThriftTypeID getType() {
return this.type;
}
}
| sircodesalotOfTheRound/parquet-mr | parquet-thrift/src/main/java/org/apache/parquet/thrift/struct/ThriftType.java | Java | apache-2.0 | 16,845 |
/*
* Copyright 2000-2014 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 org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrLabeledStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrBreakStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrContinueStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrFlowInterruptingStatement;
import java.util.ArrayList;
import java.util.List;
/**
* @author Maxim.Medvedev
*/
public class GrLabelReference implements PsiReference {
private GrFlowInterruptingStatement myStatement;
public GrLabelReference(GrFlowInterruptingStatement statement) {
myStatement = statement;
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
if (element instanceof GrLabeledStatement) {
myStatement = handleElementRename(((GrLabeledStatement)element).getName());
}
throw new IncorrectOperationException("Can't bind not to labeled statement");
}
@Override
public TextRange getRangeInElement() {
final PsiElement identifier = myStatement.getLabelIdentifier();
if (identifier == null) {
return new TextRange(-1, -2);
}
final int offsetInParent = identifier.getStartOffsetInParent();
return new TextRange(offsetInParent, offsetInParent + identifier.getTextLength());
}
@Override
public boolean isReferenceTo(PsiElement element) {
return resolve() == element;
}
@Override
@NotNull
public String getCanonicalText() {
final String name = myStatement.getLabelName();
if (name == null) return "";
return name;
}
@Override
public GrFlowInterruptingStatement handleElementRename(String newElementName) throws IncorrectOperationException {
if (myStatement instanceof GrBreakStatement) {
myStatement = (GrFlowInterruptingStatement)myStatement.replaceWithStatement(
GroovyPsiElementFactory.getInstance(myStatement.getProject()).createStatementFromText("break " + newElementName));
}
else if (myStatement instanceof GrContinueStatement) {
myStatement = (GrFlowInterruptingStatement)myStatement.replaceWithStatement(
GroovyPsiElementFactory.getInstance(myStatement.getProject()).createStatementFromText("continue " + newElementName));
}
return myStatement;
}
@Override
@NotNull
public Object[] getVariants() {
final List<PsiElement> result = new ArrayList<>();
PsiElement context = myStatement;
while (context != null) {
if (context instanceof GrLabeledStatement) {
result.add(context);
}
context = context.getContext();
}
return ArrayUtil.toObjectArray(result);
}
@Override
public boolean isSoft() {
return false;
}
@Override
public GrFlowInterruptingStatement getElement() {
return myStatement;
}
@Override
public PsiElement resolve() {
return myStatement.resolveLabel();
}
}
| asedunov/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/auxiliary/GrLabelReference.java | Java | apache-2.0 | 3,890 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.exportimport.util;
import org.jboss.logging.Logger;
import org.keycloak.exportimport.ExportImportConfig;
import org.keycloak.exportimport.ExportProvider;
import org.keycloak.exportimport.UsersExportStrategy;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.KeycloakSessionTask;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RealmRepresentation;
import java.io.IOException;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Marek Posolda</a>
*/
public abstract class MultipleStepsExportProvider implements ExportProvider {
protected final Logger logger = Logger.getLogger(getClass());
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
final RealmsHolder holder = new RealmsHolder();
KeycloakModelUtils.runJobInTransaction(factory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
List<RealmModel> realms = session.realms().getRealms();
holder.realms = realms;
}
});
for (RealmModel realm : holder.realms) {
exportRealmImpl(factory, realm.getName());
}
}
@Override
public void exportRealm(KeycloakSessionFactory factory, String realmName) throws IOException {
exportRealmImpl(factory, realmName);
}
protected void exportRealmImpl(KeycloakSessionFactory factory, final String realmName) throws IOException {
final UsersExportStrategy usersExportStrategy = ExportImportConfig.getUsersExportStrategy();
final int usersPerFile = ExportImportConfig.getUsersPerFile();
final UsersHolder usersHolder = new UsersHolder();
final boolean exportUsersIntoRealmFile = usersExportStrategy == UsersExportStrategy.REALM_FILE;
FederatedUsersHolder federatedUsersHolder = new FederatedUsersHolder();
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
RealmModel realm = session.realms().getRealmByName(realmName);
RealmRepresentation rep = ExportUtils.exportRealm(session, realm, exportUsersIntoRealmFile, true);
writeRealm(realmName + "-realm.json", rep);
logger.info("Realm '" + realmName + "' - data exported");
// Count total number of users
if (!exportUsersIntoRealmFile) {
usersHolder.totalCount = session.users().getUsersCount(realm, true);
federatedUsersHolder.totalCount = session.userFederatedStorage().getStoredUsersCount(realm);
}
}
});
if (usersExportStrategy != UsersExportStrategy.SKIP && !exportUsersIntoRealmFile) {
// We need to export users now
usersHolder.currentPageStart = 0;
// usersExportStrategy==SAME_FILE means exporting all users into single file (but separate to realm)
final int countPerPage = (usersExportStrategy == UsersExportStrategy.SAME_FILE) ? usersHolder.totalCount : usersPerFile;
while (usersHolder.currentPageStart < usersHolder.totalCount) {
if (usersHolder.currentPageStart + countPerPage < usersHolder.totalCount) {
usersHolder.currentPageEnd = usersHolder.currentPageStart + countPerPage;
} else {
usersHolder.currentPageEnd = usersHolder.totalCount;
}
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
RealmModel realm = session.realms().getRealmByName(realmName);
usersHolder.users = session.users().getUsers(realm, usersHolder.currentPageStart, usersHolder.currentPageEnd - usersHolder.currentPageStart, true);
writeUsers(realmName + "-users-" + (usersHolder.currentPageStart / countPerPage) + ".json", session, realm, usersHolder.users);
logger.info("Users " + usersHolder.currentPageStart + "-" + (usersHolder.currentPageEnd -1) + " exported");
}
});
usersHolder.currentPageStart = usersHolder.currentPageEnd;
}
}
if (usersExportStrategy != UsersExportStrategy.SKIP && !exportUsersIntoRealmFile) {
// We need to export users now
federatedUsersHolder.currentPageStart = 0;
// usersExportStrategy==SAME_FILE means exporting all users into single file (but separate to realm)
final int countPerPage = (usersExportStrategy == UsersExportStrategy.SAME_FILE) ? federatedUsersHolder.totalCount : usersPerFile;
while (federatedUsersHolder.currentPageStart < federatedUsersHolder.totalCount) {
if (federatedUsersHolder.currentPageStart + countPerPage < federatedUsersHolder.totalCount) {
federatedUsersHolder.currentPageEnd = federatedUsersHolder.currentPageStart + countPerPage;
} else {
federatedUsersHolder.currentPageEnd = federatedUsersHolder.totalCount;
}
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
RealmModel realm = session.realms().getRealmByName(realmName);
federatedUsersHolder.users = session.userFederatedStorage().getStoredUsers(realm, federatedUsersHolder.currentPageStart, federatedUsersHolder.currentPageEnd - federatedUsersHolder.currentPageStart);
writeFederatedUsers(realmName + "-federated-users-" + (federatedUsersHolder.currentPageStart / countPerPage) + ".json", session, realm, federatedUsersHolder.users);
logger.info("Users " + federatedUsersHolder.currentPageStart + "-" + (federatedUsersHolder.currentPageEnd -1) + " exported");
}
});
federatedUsersHolder.currentPageStart = federatedUsersHolder.currentPageEnd;
}
}
}
protected abstract void writeRealm(String fileName, RealmRepresentation rep) throws IOException;
protected abstract void writeUsers(String fileName, KeycloakSession session, RealmModel realm, List<UserModel> users) throws IOException;
protected abstract void writeFederatedUsers(String fileName, KeycloakSession session, RealmModel realm, List<String> users) throws IOException;
public static class RealmsHolder {
List<RealmModel> realms;
}
public static class UsersHolder {
List<UserModel> users;
int totalCount;
int currentPageStart;
int currentPageEnd;
}
public static class FederatedUsersHolder {
List<String> users;
int totalCount;
int currentPageStart;
int currentPageEnd;
}
}
| brat000012001/keycloak | services/src/main/java/org/keycloak/exportimport/util/MultipleStepsExportProvider.java | Java | apache-2.0 | 8,124 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 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.trans.steps.excelwriter;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInjectionInterface;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class ExcelWriterStepMeta extends BaseStepMeta implements StepMetaInterface {
private static Class<?> PKG = ExcelWriterStepMeta.class; // for i18n purposes, needed by Translator2!!
public static final String IF_FILE_EXISTS_REUSE = "reuse";
public static final String IF_FILE_EXISTS_CREATE_NEW = "new";
public static final String IF_SHEET_EXISTS_REUSE = "reuse";
public static final String IF_SHEET_EXISTS_CREATE_NEW = "new";
public static final String ROW_WRITE_OVERWRITE = "overwrite";
public static final String ROW_WRITE_PUSH_DOWN = "push";
/** The base name of the output file */
private String fileName;
/** what to do if file exists **/
private String ifFileExists;
private String ifSheetExists;
private boolean makeSheetActive;
private boolean forceFormulaRecalculation = false;
private boolean leaveExistingStylesUnchanged = false;
/** advanced line append options **/
private int appendOffset = 0;
private int appendEmpty = 0;
private boolean appendOmitHeader = false;
/** how to write rows **/
private String rowWritingMethod;
/** where to start writing **/
private String startingCell;
/** The file extension in case of a generated filename */
private String extension;
/** The password to protect the sheet */
private String password;
private String protectedBy;
/** Add a header at the top of the file? */
private boolean headerEnabled;
/** Add a footer at the bottom of the file? */
private boolean footerEnabled;
/** if this value is larger then 0, the text file is split up into parts of this number of lines */
private int splitEvery;
/** Flag: add the stepnr in the filename */
private boolean stepNrInFilename;
/** Flag: add the date in the filename */
private boolean dateInFilename;
/** Flag: add the filenames to result filenames */
private boolean addToResultFilenames;
/** Flag: protect the sheet */
private boolean protectsheet;
/** Flag: add the time in the filename */
private boolean timeInFilename;
/** Flag: use a template */
private boolean templateEnabled;
private boolean templateSheetEnabled;
/** the excel template */
private String templateFileName;
private String templateSheetName;
/** the excel sheet name */
private String sheetname;
/* THE FIELD SPECIFICATIONS ... */
/** The output fields */
private ExcelWriterStepField[] outputFields;
/** Flag : appendLines lines? */
private boolean appendLines;
/** Flag : Do not open new file when transformation start */
private boolean doNotOpenNewFileInit;
private boolean SpecifyFormat;
private String date_time_format;
/** Flag : auto size columns? */
private boolean autosizecolums;
/** Do we need to stream data to handle very large files? */
private boolean streamingData;
public ExcelWriterStepMeta() {
super();
}
public int getAppendOffset() {
return appendOffset;
}
public void setAppendOffset( int appendOffset ) {
this.appendOffset = appendOffset;
}
public int getAppendEmpty() {
return appendEmpty;
}
public void setAppendEmpty( int appendEmpty ) {
this.appendEmpty = appendEmpty >= 0 ? appendEmpty : 0;
}
/**
* @return Returns the dateInFilename.
*/
public boolean isDateInFilename() {
return dateInFilename;
}
/**
* @param dateInFilename
* The dateInFilename to set.
*/
public void setDateInFilename( boolean dateInFilename ) {
this.dateInFilename = dateInFilename;
}
public boolean isAppendOmitHeader() {
return appendOmitHeader;
}
public void setAppendOmitHeader( boolean appendOmitHeader ) {
this.appendOmitHeader = appendOmitHeader;
}
public String getStartingCell() {
return startingCell;
}
public void setStartingCell( String startingCell ) {
this.startingCell = startingCell;
}
public String getRowWritingMethod() {
return rowWritingMethod;
}
public void setRowWritingMethod( String rowWritingMethod ) {
this.rowWritingMethod = rowWritingMethod;
}
public String getIfFileExists() {
return ifFileExists;
}
public void setIfFileExists( String ifFileExists ) {
this.ifFileExists = ifFileExists;
}
public String getIfSheetExists() {
return ifSheetExists;
}
public void setIfSheetExists( String ifSheetExists ) {
this.ifSheetExists = ifSheetExists;
}
public String getProtectedBy() {
return protectedBy;
}
public void setProtectedBy( String protectedBy ) {
this.protectedBy = protectedBy;
}
/**
* @return Returns the extension.
*/
public String getExtension() {
return extension;
}
/**
* @param extension
* The extension to set.
*/
public void setExtension( String extension ) {
this.extension = extension;
}
/**
* @return Returns the fileName.
*/
public String getFileName() {
return fileName;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @return Returns the sheet name.
*/
public String getSheetname() {
return sheetname;
}
/**
* @param sheetname
* The sheet name.
*/
public void setSheetname( String sheetname ) {
this.sheetname = sheetname;
}
/**
* @param fileName
* The fileName to set.
*/
public void setFileName( String fileName ) {
this.fileName = fileName;
}
/**
* @param password
* teh passwoed to set.
*/
public void setPassword( String password ) {
this.password = password;
}
/**
* @return Returns the footer.
*/
public boolean isFooterEnabled() {
return footerEnabled;
}
/**
* @param footer
* The footer to set.
*/
public void setFooterEnabled( boolean footer ) {
this.footerEnabled = footer;
}
/**
* @return Returns the autosizecolums.
*/
public boolean isAutoSizeColums() {
return autosizecolums;
}
/**
* @param autosizecolums
* The autosizecolums to set.
*/
public void setAutoSizeColums( boolean autosizecolums ) {
this.autosizecolums = autosizecolums;
}
/**
* @return Returns the header.
*/
public boolean isHeaderEnabled() {
return headerEnabled;
}
/**
* @param header
* The header to set.
*/
public void setHeaderEnabled( boolean header ) {
this.headerEnabled = header;
}
public boolean isSpecifyFormat() {
return SpecifyFormat;
}
public void setSpecifyFormat( boolean SpecifyFormat ) {
this.SpecifyFormat = SpecifyFormat;
}
public String getDateTimeFormat() {
return date_time_format;
}
public void setDateTimeFormat( String date_time_format ) {
this.date_time_format = date_time_format;
}
/**
* @return Returns the splitEvery.
*/
public int getSplitEvery() {
return splitEvery;
}
/**
* @return Returns the add to result filesname.
*/
public boolean isAddToResultFiles() {
return addToResultFilenames;
}
/**
* @param addtoresultfilenamesin
* The addtoresultfilenames to set.
*/
public void setAddToResultFiles( boolean addtoresultfilenamesin ) {
this.addToResultFilenames = addtoresultfilenamesin;
}
/**
* @param splitEvery
* The splitEvery to set.
*/
public void setSplitEvery( int splitEvery ) {
this.splitEvery = splitEvery >= 0 ? splitEvery : 0;
}
/**
* @return Returns the stepNrInFilename.
*/
public boolean isStepNrInFilename() {
return stepNrInFilename;
}
/**
* @param stepNrInFilename
* The stepNrInFilename to set.
*/
public void setStepNrInFilename( boolean stepNrInFilename ) {
this.stepNrInFilename = stepNrInFilename;
}
/**
* @return Returns the timeInFilename.
*/
public boolean isTimeInFilename() {
return timeInFilename;
}
/**
* @return Returns the protectsheet.
*/
public boolean isSheetProtected() {
return protectsheet;
}
/**
* @param timeInFilename
* The timeInFilename to set.
*/
public void setTimeInFilename( boolean timeInFilename ) {
this.timeInFilename = timeInFilename;
}
/**
* @param protectsheet
* the value to set.
*/
public void setProtectSheet( boolean protectsheet ) {
this.protectsheet = protectsheet;
}
/**
* @return Returns the outputFields.
*/
public ExcelWriterStepField[] getOutputFields() {
return outputFields;
}
/**
* @param outputFields
* The outputFields to set.
*/
public void setOutputFields( ExcelWriterStepField[] outputFields ) {
this.outputFields = outputFields;
}
/**
* @return Returns the template.
*/
public boolean isTemplateEnabled() {
return templateEnabled;
}
/**
* @param template
* The template to set.
*/
public void setTemplateEnabled( boolean template ) {
this.templateEnabled = template;
}
public boolean isTemplateSheetEnabled() {
return templateSheetEnabled;
}
public void setTemplateSheetEnabled( boolean templateSheetEnabled ) {
this.templateSheetEnabled = templateSheetEnabled;
}
/**
* @return Returns the templateFileName.
*/
public String getTemplateFileName() {
return templateFileName;
}
/**
* @param templateFileName
* The templateFileName to set.
*/
public void setTemplateFileName( String templateFileName ) {
this.templateFileName = templateFileName;
}
public String getTemplateSheetName() {
return templateSheetName;
}
public void setTemplateSheetName( String templateSheetName ) {
this.templateSheetName = templateSheetName;
}
/**
* @return Returns the "do not open new file at init" flag.
*/
public boolean isDoNotOpenNewFileInit() {
return doNotOpenNewFileInit;
}
/**
* @param doNotOpenNewFileInit
* The "do not open new file at init" flag to set.
*/
public void setDoNotOpenNewFileInit( boolean doNotOpenNewFileInit ) {
this.doNotOpenNewFileInit = doNotOpenNewFileInit;
}
/**
* @return Returns the appendLines.
*/
public boolean isAppendLines() {
return appendLines;
}
/**
* @param append
* The appendLines to set.
*/
public void setAppendLines( boolean append ) {
this.appendLines = append;
}
public void setMakeSheetActive( boolean makeSheetActive ) {
this.makeSheetActive = makeSheetActive;
}
public boolean isMakeSheetActive() {
return makeSheetActive;
}
public boolean isForceFormulaRecalculation() {
return forceFormulaRecalculation;
}
public void setForceFormulaRecalculation( boolean forceFormulaRecalculation ) {
this.forceFormulaRecalculation = forceFormulaRecalculation;
}
public boolean isLeaveExistingStylesUnchanged() {
return leaveExistingStylesUnchanged;
}
public void setLeaveExistingStylesUnchanged( boolean leaveExistingStylesUnchanged ) {
this.leaveExistingStylesUnchanged = leaveExistingStylesUnchanged;
}
public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
readData( stepnode );
}
public void allocate( int nrfields ) {
outputFields = new ExcelWriterStepField[nrfields];
}
public Object clone() {
ExcelWriterStepMeta retval = (ExcelWriterStepMeta) super.clone();
int nrfields = outputFields.length;
retval.allocate( nrfields );
for ( int i = 0; i < nrfields; i++ ) {
retval.outputFields[i] = (ExcelWriterStepField) outputFields[i].clone();
}
return retval;
}
private void readData( Node stepnode ) throws KettleXMLException {
try {
headerEnabled = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "header" ) );
footerEnabled = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "footer" ) );
appendOmitHeader = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "appendOmitHeader" ) );
appendLines = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "appendLines" ) );
makeSheetActive = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "makeSheetActive" ) );
appendOffset = Const.toInt( XMLHandler.getTagValue( stepnode, "appendOffset" ), 0 );
appendEmpty = Const.toInt( XMLHandler.getTagValue( stepnode, "appendEmpty" ), 0 );
startingCell = XMLHandler.getTagValue( stepnode, "startingCell" );
rowWritingMethod = XMLHandler.getTagValue( stepnode, "rowWritingMethod" );
forceFormulaRecalculation =
"Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "forceFormulaRecalculation" ) );
leaveExistingStylesUnchanged =
"Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "leaveExistingStylesUnchanged" ) );
String addToResult = XMLHandler.getTagValue( stepnode, "add_to_result_filenames" );
if ( Const.isEmpty( addToResult ) ) {
addToResultFilenames = true;
} else {
addToResultFilenames = "Y".equalsIgnoreCase( addToResult );
}
fileName = XMLHandler.getTagValue( stepnode, "file", "name" );
extension = XMLHandler.getTagValue( stepnode, "file", "extention" );
doNotOpenNewFileInit =
"Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "do_not_open_newfile_init" ) );
stepNrInFilename = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "split" ) );
dateInFilename = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "add_date" ) );
timeInFilename = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "add_time" ) );
SpecifyFormat = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "SpecifyFormat" ) );
date_time_format = XMLHandler.getTagValue( stepnode, "file", "date_time_format" );
autosizecolums = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "autosizecolums" ) );
streamingData = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "stream_data" ) );
protectsheet = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "file", "protect_sheet" ) );
password = Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue( stepnode, "file", "password" ) );
protectedBy = XMLHandler.getTagValue( stepnode, "file", "protected_by" );
splitEvery = Const.toInt( XMLHandler.getTagValue( stepnode, "file", "splitevery" ), 0 );
templateEnabled = "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "template", "enabled" ) );
templateSheetEnabled =
"Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "template", "sheet_enabled" ) );
templateFileName = XMLHandler.getTagValue( stepnode, "template", "filename" );
templateSheetName = XMLHandler.getTagValue( stepnode, "template", "sheetname" );
sheetname = XMLHandler.getTagValue( stepnode, "file", "sheetname" );
ifFileExists = XMLHandler.getTagValue( stepnode, "file", "if_file_exists" );
ifSheetExists = XMLHandler.getTagValue( stepnode, "file", "if_sheet_exists" );
Node fields = XMLHandler.getSubNode( stepnode, "fields" );
int nrfields = XMLHandler.countNodes( fields, "field" );
allocate( nrfields );
for ( int i = 0; i < nrfields; i++ ) {
Node fnode = XMLHandler.getSubNodeByNr( fields, "field", i );
outputFields[i] = new ExcelWriterStepField();
outputFields[i].setName( XMLHandler.getTagValue( fnode, "name" ) );
outputFields[i].setType( XMLHandler.getTagValue( fnode, "type" ) );
outputFields[i].setFormat( XMLHandler.getTagValue( fnode, "format" ) );
outputFields[i].setTitle( XMLHandler.getTagValue( fnode, "title" ) );
outputFields[i].setTitleStyleCell( XMLHandler.getTagValue( fnode, "titleStyleCell" ) );
outputFields[i].setStyleCell( XMLHandler.getTagValue( fnode, "styleCell" ) );
outputFields[i].setCommentField( XMLHandler.getTagValue( fnode, "commentField" ) );
outputFields[i].setCommentAuthorField( XMLHandler.getTagValue( fnode, "commentAuthorField" ) );
outputFields[i].setFormula( XMLHandler.getTagValue( fnode, "formula" ) != null
&& XMLHandler.getTagValue( fnode, "formula" ).equalsIgnoreCase( "Y" ) );
outputFields[i].setHyperlinkField( XMLHandler.getTagValue( fnode, "hyperlinkField" ) );
}
} catch ( Exception e ) {
throw new KettleXMLException( "Unable to load step info from XML", e );
}
}
public String getNewLine( String fformat ) {
String nl = System.getProperty( "line.separator" );
if ( fformat != null ) {
if ( fformat.equalsIgnoreCase( "DOS" ) ) {
nl = "\r\n";
} else if ( fformat.equalsIgnoreCase( "UNIX" ) ) {
nl = "\n";
}
}
return nl;
}
public void setDefault() {
autosizecolums = false;
streamingData = false;
headerEnabled = true;
footerEnabled = false;
fileName = "file";
extension = "xls";
doNotOpenNewFileInit = false;
stepNrInFilename = false;
dateInFilename = false;
timeInFilename = false;
date_time_format = null;
SpecifyFormat = false;
addToResultFilenames = true;
protectsheet = false;
splitEvery = 0;
templateEnabled = false;
templateFileName = "template.xls";
sheetname = "Sheet1";
appendLines = false;
ifFileExists = IF_FILE_EXISTS_CREATE_NEW;
ifSheetExists = IF_SHEET_EXISTS_CREATE_NEW;
startingCell = "A1";
rowWritingMethod = ROW_WRITE_OVERWRITE;
appendEmpty = 0;
appendOffset = 0;
appendOmitHeader = false;
makeSheetActive = true;
forceFormulaRecalculation = false;
allocate( 0 );
}
public String[] getFiles( VariableSpace space ) {
int copies = 1;
int splits = 1;
if ( stepNrInFilename ) {
copies = 3;
}
if ( splitEvery != 0 ) {
splits = 4;
}
int nr = copies * splits;
if ( nr > 1 ) {
nr++;
}
String[] retval = new String[nr];
int i = 0;
for ( int copy = 0; copy < copies; copy++ ) {
for ( int split = 0; split < splits; split++ ) {
retval[i] = buildFilename( space, copy, split );
i++;
}
}
if ( i < nr ) {
retval[i] = "...";
}
return retval;
}
public String buildFilename( VariableSpace space, int stepnr, int splitnr ) {
SimpleDateFormat daf = new SimpleDateFormat();
// Replace possible environment variables...
String retval = space.environmentSubstitute( fileName );
String realextension = space.environmentSubstitute( extension );
Date now = new Date();
if ( SpecifyFormat && !Const.isEmpty( date_time_format ) ) {
daf.applyPattern( date_time_format );
String dt = daf.format( now );
retval += dt;
} else {
if ( dateInFilename ) {
daf.applyPattern( "yyyMMdd" );
String d = daf.format( now );
retval += "_" + d;
}
if ( timeInFilename ) {
daf.applyPattern( "HHmmss" );
String t = daf.format( now );
retval += "_" + t;
}
}
if ( stepNrInFilename ) {
retval += "_" + stepnr;
}
if ( splitEvery > 0 ) {
retval += "_" + splitnr;
}
if ( realextension != null && realextension.length() != 0 ) {
retval += "." + realextension;
}
return retval;
}
public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
VariableSpace space, Repository repository, IMetaStore metaStore ) {
if ( r == null ) {
r = new RowMeta(); // give back values
}
// No values are added to the row in this type of step
}
public String getXML() {
StringBuffer retval = new StringBuffer( 800 );
retval.append( " " ).append( XMLHandler.addTagValue( "header", headerEnabled ) );
retval.append( " " ).append( XMLHandler.addTagValue( "footer", footerEnabled ) );
retval.append( " " ).append( XMLHandler.addTagValue( "makeSheetActive", makeSheetActive ) );
retval.append( " " ).append( XMLHandler.addTagValue( "rowWritingMethod", rowWritingMethod ) );
retval.append( " " ).append( XMLHandler.addTagValue( "startingCell", startingCell ) );
retval.append( " " ).append( XMLHandler.addTagValue( "appendOmitHeader", appendOmitHeader ) );
retval.append( " " ).append( XMLHandler.addTagValue( "appendOffset", appendOffset ) );
retval.append( " " ).append( XMLHandler.addTagValue( "appendEmpty", appendEmpty ) );
retval.append( " " ).append( XMLHandler.addTagValue( "rowWritingMethod", rowWritingMethod ) );
retval.append( " " ).append(
XMLHandler.addTagValue( "forceFormulaRecalculation", forceFormulaRecalculation ) );
retval.append( " " ).append(
XMLHandler.addTagValue( "leaveExistingStylesUnchanged", leaveExistingStylesUnchanged ) );
retval.append( " " + XMLHandler.addTagValue( "appendLines", appendLines ) );
retval.append( " " + XMLHandler.addTagValue( "add_to_result_filenames", addToResultFilenames ) );
retval.append( " <file>" ).append( Const.CR );
retval.append( " " ).append( XMLHandler.addTagValue( "name", fileName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "extention", extension ) );
retval.append( " " ).append( XMLHandler.addTagValue( "do_not_open_newfile_init", doNotOpenNewFileInit ) );
retval.append( " " ).append( XMLHandler.addTagValue( "split", stepNrInFilename ) );
retval.append( " " ).append( XMLHandler.addTagValue( "add_date", dateInFilename ) );
retval.append( " " ).append( XMLHandler.addTagValue( "add_time", timeInFilename ) );
retval.append( " " ).append( XMLHandler.addTagValue( "SpecifyFormat", SpecifyFormat ) );
retval.append( " " ).append( XMLHandler.addTagValue( "date_time_format", date_time_format ) );
retval.append( " " ).append( XMLHandler.addTagValue( "sheetname", sheetname ) );
retval.append( " " ).append( XMLHandler.addTagValue( "autosizecolums", autosizecolums ) );
retval.append( " " ).append( XMLHandler.addTagValue( "stream_data", streamingData ) );
retval.append( " " ).append( XMLHandler.addTagValue( "protect_sheet", protectsheet ) );
retval.append( " " ).append(
XMLHandler.addTagValue( "password", Encr.encryptPasswordIfNotUsingVariables( password ) ) );
retval.append( " " ).append( XMLHandler.addTagValue( "protected_by", protectedBy ) );
retval.append( " " ).append( XMLHandler.addTagValue( "splitevery", splitEvery ) );
retval.append( " " ).append( XMLHandler.addTagValue( "if_file_exists", ifFileExists ) );
retval.append( " " ).append( XMLHandler.addTagValue( "if_sheet_exists", ifSheetExists ) );
retval.append( " </file>" ).append( Const.CR );
retval.append( " <template>" ).append( Const.CR );
retval.append( " " ).append( XMLHandler.addTagValue( "enabled", templateEnabled ) );
retval.append( " " ).append( XMLHandler.addTagValue( "sheet_enabled", templateSheetEnabled ) );
retval.append( " " ).append( XMLHandler.addTagValue( "filename", templateFileName ) );
retval.append( " " ).append( XMLHandler.addTagValue( "sheetname", templateSheetName ) );
retval.append( " </template>" ).append( Const.CR );
retval.append( " <fields>" ).append( Const.CR );
for ( int i = 0; i < outputFields.length; i++ ) {
ExcelWriterStepField field = outputFields[i];
if ( field.getName() != null && field.getName().length() != 0 ) {
retval.append( " <field>" ).append( Const.CR );
retval.append( " " ).append( XMLHandler.addTagValue( "name", field.getName() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "type", field.getTypeDesc() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "format", field.getFormat() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "title", field.getTitle() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "titleStyleCell", field.getTitleStyleCell() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "styleCell", field.getStyleCell() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "commentField", field.getCommentField() ) );
retval.append( " " ).append(
XMLHandler.addTagValue( "commentAuthorField", field.getCommentAuthorField() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "formula", field.isFormula() ) );
retval.append( " " ).append( XMLHandler.addTagValue( "hyperlinkField", field.getHyperlinkField() ) );
retval.append( " </field>" ).append( Const.CR );
}
}
retval.append( " </fields>" ).append( Const.CR );
return retval.toString();
}
public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
try {
headerEnabled = rep.getStepAttributeBoolean( id_step, "header" );
footerEnabled = rep.getStepAttributeBoolean( id_step, "footer" );
makeSheetActive = rep.getStepAttributeBoolean( id_step, "makeSheetActive" );
appendOmitHeader = rep.getStepAttributeBoolean( id_step, "appendOmitHeader" );
startingCell = rep.getStepAttributeString( id_step, "startingCell" );
appendEmpty = (int) rep.getStepAttributeInteger( id_step, "appendEmpty" );
appendOffset = (int) rep.getStepAttributeInteger( id_step, "appendOffset" );
rowWritingMethod = rep.getStepAttributeString( id_step, "rowWritingMethod" );
appendLines = rep.getStepAttributeBoolean( id_step, "appendLines" );
forceFormulaRecalculation = rep.getStepAttributeBoolean( id_step, "forceFormulaRecalculation" );
leaveExistingStylesUnchanged = rep.getStepAttributeBoolean( id_step, "leaveExistingStylesUnchanged" );
String addToResult = rep.getStepAttributeString( id_step, "add_to_result_filenames" );
if ( Const.isEmpty( addToResult ) ) {
addToResultFilenames = true;
} else {
addToResultFilenames = rep.getStepAttributeBoolean( id_step, "add_to_result_filenames" );
}
fileName = rep.getStepAttributeString( id_step, "file_name" );
extension = rep.getStepAttributeString( id_step, "file_extention" );
doNotOpenNewFileInit = rep.getStepAttributeBoolean( id_step, "do_not_open_newfile_init" );
splitEvery = (int) rep.getStepAttributeInteger( id_step, "file_split" );
stepNrInFilename = rep.getStepAttributeBoolean( id_step, "file_add_stepnr" );
dateInFilename = rep.getStepAttributeBoolean( id_step, "file_add_date" );
timeInFilename = rep.getStepAttributeBoolean( id_step, "file_add_time" );
SpecifyFormat = rep.getStepAttributeBoolean( id_step, "SpecifyFormat" );
date_time_format = rep.getStepAttributeString( id_step, "date_time_format" );
autosizecolums = rep.getStepAttributeBoolean( id_step, "autosizecolums" );
streamingData = rep.getStepAttributeBoolean( id_step, "stream_data" );
protectsheet = rep.getStepAttributeBoolean( id_step, "protect_sheet" );
password = Encr.decryptPasswordOptionallyEncrypted( rep.getStepAttributeString( id_step, "password" ) );
protectedBy = rep.getStepAttributeString( id_step, "protected_by" );
templateEnabled = rep.getStepAttributeBoolean( id_step, "template_enabled" );
templateFileName = rep.getStepAttributeString( id_step, "template_filename" );
templateSheetEnabled = rep.getStepAttributeBoolean( id_step, "template_sheet_enabled" );
templateSheetName = rep.getStepAttributeString( id_step, "template_sheetname" );
sheetname = rep.getStepAttributeString( id_step, "sheetname" );
ifFileExists = rep.getStepAttributeString( id_step, "if_file_exists" );
ifSheetExists = rep.getStepAttributeString( id_step, "if_sheet_exists" );
int nrfields = rep.countNrStepAttributes( id_step, "field_name" );
allocate( nrfields );
for ( int i = 0; i < nrfields; i++ ) {
outputFields[i] = new ExcelWriterStepField();
outputFields[i].setName( rep.getStepAttributeString( id_step, i, "field_name" ) );
outputFields[i].setType( rep.getStepAttributeString( id_step, i, "field_type" ) );
outputFields[i].setFormat( rep.getStepAttributeString( id_step, i, "field_format" ) );
outputFields[i].setTitle( rep.getStepAttributeString( id_step, i, "field_title" ) );
outputFields[i].setTitleStyleCell( rep.getStepAttributeString( id_step, i, "field_title_style_cell" ) );
outputFields[i].setStyleCell( rep.getStepAttributeString( id_step, i, "field_style_cell" ) );
outputFields[i].setCommentField( rep.getStepAttributeString( id_step, i, "field_comment_field" ) );
outputFields[i].setCommentAuthorField( rep.getStepAttributeString(
id_step, i, "field_comment_author_field" ) );
outputFields[i].setFormula( rep.getStepAttributeBoolean( id_step, i, "field_formula" ) );
outputFields[i].setHyperlinkField( rep.getStepAttributeString( id_step, i, "field_hyperlink_field" ) );
}
} catch ( Exception e ) {
throw new KettleException( "Unexpected error reading step information from the repository", e );
}
}
public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
try {
rep.saveStepAttribute( id_transformation, id_step, "header", headerEnabled );
rep.saveStepAttribute( id_transformation, id_step, "footer", footerEnabled );
rep.saveStepAttribute( id_transformation, id_step, "makeSheetActive", makeSheetActive );
rep.saveStepAttribute( id_transformation, id_step, "startingCell", startingCell );
rep.saveStepAttribute( id_transformation, id_step, "appendOmitHeader", appendOmitHeader );
rep.saveStepAttribute( id_transformation, id_step, "appendEmpty", appendEmpty );
rep.saveStepAttribute( id_transformation, id_step, "appendOffset", appendOffset );
rep.saveStepAttribute( id_transformation, id_step, "rowWritingMethod", rowWritingMethod );
rep.saveStepAttribute( id_transformation, id_step, "appendLines", appendLines );
rep.saveStepAttribute( id_transformation, id_step, "add_to_result_filenames", addToResultFilenames );
rep.saveStepAttribute( id_transformation, id_step, "file_name", fileName );
rep.saveStepAttribute( id_transformation, id_step, "do_not_open_newfile_init", doNotOpenNewFileInit );
rep.saveStepAttribute( id_transformation, id_step, "forceFormulaRecalculation", forceFormulaRecalculation );
rep.saveStepAttribute(
id_transformation, id_step, "leaveExistingStylesUnchanged", leaveExistingStylesUnchanged );
rep.saveStepAttribute( id_transformation, id_step, "file_extention", extension );
rep.saveStepAttribute( id_transformation, id_step, "file_split", splitEvery );
rep.saveStepAttribute( id_transformation, id_step, "file_add_stepnr", stepNrInFilename );
rep.saveStepAttribute( id_transformation, id_step, "file_add_date", dateInFilename );
rep.saveStepAttribute( id_transformation, id_step, "file_add_time", timeInFilename );
rep.saveStepAttribute( id_transformation, id_step, "SpecifyFormat", SpecifyFormat );
rep.saveStepAttribute( id_transformation, id_step, "date_time_format", date_time_format );
rep.saveStepAttribute( id_transformation, id_step, "autosizecolums", autosizecolums );
rep.saveStepAttribute( id_transformation, id_step, "stream_data", streamingData );
rep.saveStepAttribute( id_transformation, id_step, "protect_sheet", protectsheet );
rep.saveStepAttribute( id_transformation, id_step, "protected_by", protectedBy );
rep.saveStepAttribute( id_transformation, id_step, "password", Encr
.encryptPasswordIfNotUsingVariables( password ) );
rep.saveStepAttribute( id_transformation, id_step, "template_enabled", templateEnabled );
rep.saveStepAttribute( id_transformation, id_step, "template_filename", templateFileName );
rep.saveStepAttribute( id_transformation, id_step, "template_sheet_enabled", templateSheetEnabled );
rep.saveStepAttribute( id_transformation, id_step, "template_sheetname", templateSheetName );
rep.saveStepAttribute( id_transformation, id_step, "sheetname", sheetname );
rep.saveStepAttribute( id_transformation, id_step, "if_file_exists", ifFileExists );
rep.saveStepAttribute( id_transformation, id_step, "if_sheet_exists", ifSheetExists );
for ( int i = 0; i < outputFields.length; i++ ) {
ExcelWriterStepField field = outputFields[i];
rep.saveStepAttribute( id_transformation, id_step, i, "field_name", field.getName() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_type", field.getTypeDesc() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_format", field.getFormat() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_title", field.getTitle() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_title_style_cell", field.getTitleStyleCell() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_style_cell", field.getStyleCell() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_comment_field", field.getCommentField() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_comment_author_field", field
.getCommentAuthorField() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_formula", field.isFormula() );
rep.saveStepAttribute( id_transformation, id_step, i, "field_hyperlink_field", field.getHyperlinkField() );
}
} catch ( Exception e ) {
throw new KettleException( "Unable to save step information to the repository for id_step=" + id_step, e );
}
}
public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
Repository repository, IMetaStore metaStore ) {
CheckResult cr;
// Check output fields
if ( prev != null && prev.size() > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "ExcelWriterStepMeta.CheckResult.FieldsReceived", "" + prev.size() ), stepMeta );
remarks.add( cr );
String error_message = "";
boolean error_found = false;
// Starting from selected fields in ...
for ( int i = 0; i < outputFields.length; i++ ) {
int idx = prev.indexOfValue( outputFields[i].getName() );
if ( idx < 0 ) {
error_message += "\t\t" + outputFields[i].getName() + Const.CR;
error_found = true;
}
}
if ( error_found ) {
error_message =
BaseMessages.getString( PKG, "ExcelWriterStepMeta.CheckResult.FieldsNotFound", error_message );
cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "ExcelWriterStepMeta.CheckResult.AllFieldsFound" ), stepMeta );
remarks.add( cr );
}
}
// See if we have input streams leading to this step!
if ( input.length > 0 ) {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(
PKG, "ExcelWriterStepMeta.CheckResult.ExpectedInputOk" ), stepMeta );
remarks.add( cr );
} else {
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(
PKG, "ExcelWriterStepMeta.CheckResult.ExpectedInputError" ), stepMeta );
remarks.add( cr );
}
cr =
new CheckResult( CheckResultInterface.TYPE_RESULT_COMMENT, BaseMessages.getString(
PKG, "ExcelWriterStepMeta.CheckResult.FilesNotChecked" ), stepMeta );
remarks.add( cr );
}
/**
* @param space
* the variable space to use
* @param definitions
* @param resourceNamingInterface
* @param repository
* The repository to optionally load other resources from (to be converted to XML)
* @param metaStore
* the metaStore in which non-kettle metadata could reside.
*
* @return the filename of the exported resource
*/
public String exportResources( VariableSpace space, Map<String, ResourceDefinition> definitions,
ResourceNamingInterface resourceNamingInterface, Repository repository, IMetaStore metaStore ) throws KettleException {
try {
// The object that we're modifying here is a copy of the original!
// So let's change the filename from relative to absolute by grabbing the file object...
//
if ( !Const.isEmpty( fileName ) ) {
FileObject fileObject = KettleVFS.getFileObject( space.environmentSubstitute( fileName ), space );
fileName = resourceNamingInterface.nameResource( fileObject, space, true );
}
if ( !Const.isEmpty( templateFileName ) ) {
FileObject fileObject = KettleVFS.getFileObject( space.environmentSubstitute( templateFileName ), space );
templateFileName = resourceNamingInterface.nameResource( fileObject, space, true );
}
return null;
} catch ( Exception e ) {
throw new KettleException( e );
}
}
@Override
public StepMetaInjectionInterface getStepMetaInjectionInterface() {
return new ExcelWriterMetaInjection( this );
}
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr,
TransMeta transMeta, Trans trans ) {
return new ExcelWriterStep( stepMeta, stepDataInterface, cnr, transMeta, trans );
}
public StepDataInterface getStepData() {
return new ExcelWriterStepData();
}
public String[] getUsedLibraries() {
return new String[0];
}
/**
* @return the streamingData
*/
public boolean isStreamingData() {
return streamingData;
}
/**
* @param streamingData
* the streamingData to set
*/
public void setStreamingData( boolean streamingData ) {
this.streamingData = streamingData;
}
}
| mattyb149/pentaho-kettle | engine/src/org/pentaho/di/trans/steps/excelwriter/ExcelWriterStepMeta.java | Java | apache-2.0 | 40,842 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-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.sakaiproject.util;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
/**
* <p>
* Load the available Sakai components into the shared component manager's Spring ApplicationContext
* </p>
*/
public class ComponentsLoader
{
/** Our logger */
private static Logger M_log = LoggerFactory.getLogger(ComponentsLoader.class);
/** Folder containing override definitions for beans */
private File overridesFolder;
public ComponentsLoader()
{
this(null);
}
public ComponentsLoader(File overridesFolder)
{
this.overridesFolder = overridesFolder;
}
/**
*
*/
public void load(ConfigurableApplicationContext ac, String componentsRoot)
{
try
{
// get a list of the folders in the root
File root = new File(componentsRoot);
// make sure it's a dir.
if (!root.isDirectory())
{
M_log.warn("load: root not directory: " + componentsRoot);
return;
}
// what component packages are there?
File[] packageArray = root.listFiles();
if (packageArray == null)
{
M_log.warn("load: empty directory: " + componentsRoot);
return;
}
List<File> packages = Arrays.asList(packageArray);
// assure a consistent order - sort these files
Collections.sort(packages);
// for testing, we might reverse load order
if (System.getProperty("sakai.components.reverse.load") != null) {
Collections.reverse(packages);
}
M_log.info("load: loading components from: " + componentsRoot);
// process the packages
for (File packageDir : packages)
{
// if a valid components directory
if (validComponentsPackage(packageDir))
{
loadComponentPackage(packageDir, ac);
}
else
{
M_log.warn("load: skipping non-package entry: " + packageDir);
}
}
}
catch (Exception e) {
M_log.error("load: exception: " + e, e);
}
}
/**
* Load one component package into the AC
*
* @param dir
* The file path to the component package
* @param ac
* The ApplicationContext to load into
*/
protected void loadComponentPackage(File dir, ConfigurableApplicationContext ac)
{
// setup the classloader onto the thread
ClassLoader current = Thread.currentThread().getContextClassLoader();
ClassLoader loader = newPackageClassLoader(dir);
M_log.info("loadComponentPackage: " + dir);
Thread.currentThread().setContextClassLoader(loader);
File xml = null;
try
{
// load this xml file
File webinf = new File(dir, "WEB-INF");
xml = new File(webinf, "components.xml");
// make a reader
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) ac.getBeanFactory());
// In Spring 2, classes aren't loaded during bean parsing unless this
// classloader property is set.
reader.setBeanClassLoader(loader);
List<Resource> beanDefList = new ArrayList<Resource>();
beanDefList.add(new FileSystemResource(xml.getCanonicalPath()));
// Load the demo components, if necessary
File demoXml = new File(webinf, "components-demo.xml");
if("true".equalsIgnoreCase(System.getProperty("sakai.demo")))
{
if(M_log.isDebugEnabled()) M_log.debug("Attempting to load demo components");
if(demoXml.exists())
{
if(M_log.isInfoEnabled()) M_log.info("Loading demo components from " + dir);
beanDefList.add(new FileSystemResource(demoXml.getCanonicalPath()));
}
}
else
{
if(demoXml.exists())
{
// Only log that we're skipping the demo components if they exist
if(M_log.isInfoEnabled()) M_log.info("Skipping demo components from " + dir);
}
}
if (overridesFolder != null) {
File override = new File(overridesFolder, dir.getName()+ ".xml");
if (override.isFile()) {
beanDefList.add(new FileSystemResource(override.getCanonicalPath()));
if(M_log.isInfoEnabled()) M_log.info("Overriding component definitions with "+ override);
}
}
reader.loadBeanDefinitions(beanDefList.toArray(new Resource[0]));
}
catch (Exception e)
{
M_log.error("loadComponentPackage: exception loading: " + xml + " : " + e, e);
}
finally
{
// restore the context loader
Thread.currentThread().setContextClassLoader(current);
}
}
/**
* Test if this File is a valid components package directory.
*
* @param dir
* The file to test
* @return true if it is a valid components package directory, false if not.
*/
protected boolean validComponentsPackage(File dir)
{
// valid if this is a directory with a WEB-INF directory below with a components.xml file
if ((dir != null) && (dir.isDirectory()))
{
File webinf = new File(dir, "WEB-INF");
if ((webinf != null) && (webinf.isDirectory()))
{
File xml = new File(webinf, "components.xml");
if ((xml != null) && (xml.isFile()))
{
return true;
}
}
}
return false;
}
/**
* Create the class loader for this component package
*
* @param dir
* The package's root directory.
* @return A class loader, whose parent is this class's loader, which has the classes/ and jars for this component.
*/
protected ClassLoader newPackageClassLoader(File dir)
{
// collect as a List, turn into an array after
List urls = new Vector();
File webinf = new File(dir, "WEB-INF");
// put classes/ on the classpath
File classes = new File(webinf, "classes");
if ((classes != null) && (classes.isDirectory()))
{
try {
URL url = new URL("file:" + classes.getCanonicalPath() + "/");
urls.add(url);
} catch (Exception e) {
M_log.warn("Bad url for classes: "+classes.getPath()+" : "+e);
}
}
// put each .jar file onto the classpath
File lib = new File(webinf, "lib");
if ((lib != null) && (lib.isDirectory()))
{
File[] jars = lib.listFiles(new FileFilter()
{
public boolean accept(File file)
{
return (file.isFile() && file.getName().endsWith(".jar"));
}
});
if (jars != null)
{
// We sort them so that we get predictable results when loading classes.
// Otherwise sometimes you can end up with one class and other times you can end up with another
// depending on the order the listing is stored on the filesystem.
Arrays.sort(jars);
for (int j = 0; j < jars.length; j++)
{
if (jars[j] != null) {
try {
URL url = new URL("file:" + jars[j].getCanonicalPath());
urls.add(url);
} catch (Exception e) {
M_log.warn("Bad url for jar: "+jars[j].getPath()+" : "+e);
}
}
}
}
}
// make the array from the list
URL[] urlArray = (URL[]) urls.toArray(new URL[urls.size()]);
ClassLoader loader = null;
// Check to see if Terracotta clustering is turned on
// String clusterTerracotta = ServerConfigurationService.getString("cluster.terracotta","false");
String clusterTerracotta = System.getProperty("sakai.cluster.terracotta");
if ("true".equals(clusterTerracotta)) {
// If Terracotta clustering is turned on then use the Special Terracotta Class loader
loader = new TerracottaClassLoader(urlArray, getClass().getClassLoader(), dir.getName());
} else {
// Terracotta clustering is turned off, so use the normal URLClassLoader
loader = new URLClassLoader(urlArray, getClass().getClassLoader());
}
return loader;
}
}
| ouit0408/sakai | kernel/component-manager/src/main/java/org/sakaiproject/util/ComponentsLoader.java | Java | apache-2.0 | 8,989 |
/*
* Copyright 2001-2013 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.jetbrains.java.generate.element;
import com.intellij.openapi.util.text.StringUtil;
/**
* This is a method element containing information about the method.
*
* @see ElementFactory
*/
@SuppressWarnings({"UnusedDeclaration"})
public class MethodElement extends AbstractElement implements Element {
private String methodName;
private String fieldName;
private boolean modifierAbstract;
private boolean modifierSynchronized;
private boolean returnTypeVoid;
private boolean getter;
private boolean deprecated;
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
@Override
public String getAccessor() {
return methodName + "()";
}
public boolean isModifierAbstract() {
return modifierAbstract;
}
public void setModifierAbstract(boolean modifierAbstract) {
this.modifierAbstract = modifierAbstract;
}
/**
* Exists for compatibility with old templates
*/
public boolean isModifierSynchronzied() {
return isModifierSynchronized();
}
public boolean isModifierSynchronized() {
return modifierSynchronized;
}
public void setModifierSynchronized(boolean modifierSynchronized) {
this.modifierSynchronized = modifierSynchronized;
}
public boolean isReturnTypeVoid() {
return returnTypeVoid;
}
public void setReturnTypeVoid(boolean returnTypeVoid) {
this.returnTypeVoid = returnTypeVoid;
}
public boolean isGetter() {
return getter;
}
public void setGetter(boolean getter) {
this.getter = getter;
}
public boolean isDeprecated() {
return deprecated;
}
public void setDeprecated(boolean deprecated) {
this.deprecated = deprecated;
}
/**
* Performs a regular expression matching the methodname.
*
* @param regexp regular expression.
* @return true if the methodname matches the regular expression.
* @throws IllegalArgumentException is throw if the given input is invalid (an empty String) or a pattern matching error.
*/
public boolean matchName(String regexp) throws IllegalArgumentException {
if (StringUtil.isEmpty(regexp)) {
throw new IllegalArgumentException("Can't perform regular expression since the given input is empty. Check the Method body velocity code: regexp='" + regexp + "'");
}
return methodName.matches(regexp);
}
public String toString() {
return super.toString() + " ::: MethodElement{" +
"fieldName='" + fieldName + "'" +
", methodName='" + methodName + "'" +
", modifierAbstract=" + modifierAbstract +
", modifierSynchronized=" + modifierSynchronized +
", returnTypeVoid=" + returnTypeVoid +
", getter=" + getter +
", deprecated=" + deprecated +
"}";
}
}
| jwren/intellij-community | plugins/generate-tostring/src/org/jetbrains/java/generate/element/MethodElement.java | Java | apache-2.0 | 3,843 |
package com.intellij.refactoring.classMembers;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
/**
* Nikolay.Tropin
* 8/23/13
*/
public abstract class AbstractMemberInfoModel<T extends PsiElement, M extends MemberInfoBase<T>> implements MemberInfoModel<T, M> {
@Override
public boolean isMemberEnabled(M member) {
return true;
}
@Override
public boolean isCheckedWhenDisabled(M member) {
return false;
}
@Override
public boolean isAbstractEnabled(M member) {
return false;
}
@Override
public boolean isAbstractWhenDisabled(M member) {
return false;
}
@Override
public Boolean isFixedAbstract(M member) {
return null;
}
@Override
public int checkForProblems(@NotNull M member) {
return OK;
}
@Override
public String getTooltipText(M member) {
return null;
}
@Override
public void memberInfoChanged(@NotNull MemberInfoChange<T, M> event) {
}
}
| paplorinc/intellij-community | platform/lang-api/src/com/intellij/refactoring/classMembers/AbstractMemberInfoModel.java | Java | apache-2.0 | 961 |
/*
* 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.value.basic;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.modeshape.common.annotation.Immutable;
import org.modeshape.common.collection.SingleIterator;
import org.modeshape.common.text.Inflector;
import org.modeshape.common.text.TextEncoder;
import org.modeshape.common.util.CheckArg;
import org.modeshape.jcr.GraphI18n;
import org.modeshape.jcr.value.InvalidPathException;
import org.modeshape.jcr.value.Name;
import org.modeshape.jcr.value.NamespaceRegistry;
import org.modeshape.jcr.value.Path;
/**
* Optimized implementation of {@link Path} that serves as the root path.
*/
@Immutable
public class RootPath extends AbstractPath {
/**
* The serializable version. Version {@value}
*/
private static final long serialVersionUID = 1L;
public static final Path INSTANCE = new RootPath();
private static final Path.Segment[] EMPTY_SEGMENT_ARRAY = new Path.Segment[] {};
private static final List<Path.Segment> EMPTY_SEGMENT_LIST = Collections.emptyList();
private RootPath() {
}
@Override
public Path getAncestor( int degree ) {
CheckArg.isNonNegative(degree, "degree");
if (degree == 0) {
return this;
}
String msg = GraphI18n.pathAncestorDegreeIsInvalid.text(this.getString(), Inflector.getInstance().ordinalize(degree));
throw new InvalidPathException(msg);
}
@Override
protected Iterator<Segment> getSegmentsOfParent() {
return EMPTY_PATH_ITERATOR;
}
@Override
public Path getCanonicalPath() {
return this;
}
@Override
public Path getCommonAncestor( Path that ) {
CheckArg.isNotNull(that, "that");
return this;
}
@Override
public Segment getLastSegment() {
return null;
}
@Override
public boolean endsWith( Name nameOfLastSegment ) {
return false;
}
@Override
public boolean endsWith( Name nameOfLastSegment,
int snsIndex ) {
return false;
}
@Override
public Path getNormalizedPath() {
return this;
}
@Override
public Path relativeToRoot() {
return BasicPath.SELF_PATH;
}
@Override
public Path resolve( Path relativePath ) {
CheckArg.isNotNull(relativePath, "relative path");
if (relativePath.isAbsolute()) {
String msg = GraphI18n.pathIsNotRelative.text(relativePath);
throw new InvalidPathException(msg);
}
// Make an absolute path out of the supplied relative path ...
return new BasicPath(relativePath.getSegmentsList(), true).getNormalizedPath();
}
@Override
public Path getParent() {
return null;
}
@Override
public Segment getSegment( int index ) {
CheckArg.isNonNegative(index, "index");
EMPTY_SEGMENT_LIST.get(index); // throws IndexOutOfBoundsException
return null;
}
@Override
public Segment[] getSegmentsArray() {
// Can return the same array every time, since it's empty ...
return EMPTY_SEGMENT_ARRAY;
}
@Override
public List<Segment> getSegmentsList() {
return EMPTY_SEGMENT_LIST;
}
@Override
public String getString() {
return Path.DELIMITER_STR;
}
@Override
public String getString( TextEncoder encoder ) {
return Path.DELIMITER_STR;
}
@Override
public String getString( NamespaceRegistry namespaceRegistry ) {
CheckArg.isNotNull(namespaceRegistry, "namespaceRegistry");
return Path.DELIMITER_STR;
}
@Override
public String getString( NamespaceRegistry namespaceRegistry,
TextEncoder encoder ) {
CheckArg.isNotNull(namespaceRegistry, "namespaceRegistry");
return Path.DELIMITER_STR;
}
@Override
public String getString( NamespaceRegistry namespaceRegistry,
TextEncoder encoder,
TextEncoder delimiterEncoder ) {
return (delimiterEncoder == null) ? DELIMITER_STR : delimiterEncoder.encode(DELIMITER_STR);
}
@Override
public boolean hasSameAncestor( Path that ) {
CheckArg.isNotNull(that, "that");
return true;
}
@Override
public boolean isAbsolute() {
return true;
}
@Override
public boolean isAncestorOf( Path descendant ) {
CheckArg.isNotNull(descendant, "descendant");
return !descendant.isRoot();
}
@Override
public boolean isAtOrAbove( Path other ) {
CheckArg.isNotNull(other, "other");
return true;
}
@Override
public boolean isAtOrBelow( Path other ) {
CheckArg.isNotNull(other, "other");
return other.isRoot();
}
@Override
public boolean isDescendantOf( Path ancestor ) {
CheckArg.isNotNull(ancestor, "ancestor");
return false;
}
@Override
public boolean isNormalized() {
return true;
}
@Override
public boolean isRoot() {
return true;
}
@Override
public boolean isSameAs( Path other ) {
CheckArg.isNotNull(other, "other");
return other.isRoot();
}
@Override
public Iterator<Segment> iterator() {
return EMPTY_SEGMENT_LIST.iterator();
}
@Override
public Iterator<Path> pathsFromRoot() {
return new SingleIterator<Path>(this);
}
@Override
public int size() {
return 0;
}
@Override
public Path subpath( int beginIndex ) {
CheckArg.isNonNegative(beginIndex, "beginIndex");
if (beginIndex == 0) return this;
EMPTY_SEGMENT_LIST.get(1); // throws IndexOutOfBoundsException
return null;
}
@Override
public Path subpath( int beginIndex,
int endIndex ) {
CheckArg.isNonNegative(beginIndex, "beginIndex");
CheckArg.isNonNegative(endIndex, "endIndex");
if (endIndex >= 1) {
EMPTY_SEGMENT_LIST.get(endIndex); // throws IndexOutOfBoundsException
}
return this;
}
@Override
public int compareTo( Path other ) {
return other.isRoot() ? 0 : -1;
}
@Override
public boolean equals( Object obj ) {
if (obj == this) return true;
if (obj instanceof Path) {
Path that = (Path)obj;
return that.isRoot();
}
return false;
}
@Override
public int hashCode() {
return 1;
}
}
| weebl2000/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/value/basic/RootPath.java | Java | apache-2.0 | 7,207 |
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import org.apache.commons.lang3.StringUtils;
/**
* 对象操作工具类, 继承org.apache.commons.lang3.ObjectUtils类
* @author ThinkGem
* @version 2014-6-29
*/
public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils {
/**
* 注解到对象复制,只复制能匹配上的方法。
* @param annotation
* @param object
*/
public static void annotationToObject(Object annotation, Object object){
if (annotation != null){
Class<?> annotationClass = annotation.getClass();
Class<?> objectClass = object.getClass();
for (Method m : objectClass.getMethods()){
if (StringUtils.startsWith(m.getName(), "set")){
try {
String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
Object obj = annotationClass.getMethod(s).invoke(annotation);
if (obj != null && !"".equals(obj.toString())){
if (object == null){
object = objectClass.newInstance();
}
m.invoke(object, obj);
}
} catch (Exception e) {
// 忽略所有设置失败方法
}
}
}
}
}
/**
* 序列化对象
* @param object
* @return
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
if (object != null){
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 反序列化对象
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
if (bytes != null && bytes.length > 0){
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| quangou365/sub | subadmin/src/main/java/com/thinkgem/jeesite/common/utils/ObjectUtils.java | Java | apache-2.0 | 2,257 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2015 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.core.extension;
public enum KettleExtensionPoint {
// Some transformation points
//
TransformationPrepareExecution( "TransformationPrepareExecution", "A transformation begins to prepare execution" ),
TransformationStartThreads( "TransformationStartThreads", "A transformation begins to start" ),
TransformationStart( "TransformationStart", "A transformation has started" ),
TransformationHeartbeat( "TransformationHeartbeat",
"A signal sent at regular intervals to indicate that the transformation is still active" ),
TransformationFinish( "TransformationFinish", "A transformation finishes" ),
TransformationMetaLoaded( "TransformationMetaLoaded", "Transformation metadata was loaded" ),
TransPainterArrow( "TransPainterArrow", "Draw additional information on top of a transformation hop (arrow)" ),
TransPainterStep( "TransPainterStep", "Draw additional information on top of a transformation step icon" ),
TransPainterStart( "TransPainterStart", "Draw transformation or plugin metadata at the start (below the rest)" ),
TransPainterEnd( "TransPainterEnd", "Draw transformation or plugin metadata at the end (on top of all the rest)" ),
TransGraphMouseDown( "TransGraphMouseDown", "A left or right button was clicked in a transformation" ),
TransBeforeOpen( "TransBeforeOpen", "A transformation file is about to be opened" ),
TransAfterOpen( "TransAfterOpen", "A transformation file was opened" ),
TransBeforeSave( "TransBeforeSave", "A transformation file is about to be saved" ),
TransAfterSave( "TransAfterSave", "A transformation file was saved" ),
TransBeforeClose( "TransBeforeClose", "A transformation file is about to be closed" ),
TransAfterClose( "TransAfterClose", "A transformation file was closed" ),
TransChanged( "TransChanged", "A transformation has been changed" ),
TransStepRightClick( "TransStepRightClick", "A right button was clicked on a step" ),
TransGraphMouseDoubleClick( "TransGraphMouseDoubleClick",
"A left or right button was double-clicked in a transformation" ),
SpoonTransMetaExecutionStart( "SpoonTransMetaExecutionStart",
"Spoon initiates the execution of a trans (TransMeta)" ),
SpoonTransExecutionConfiguration( "SpoonTransExecutionConfiguration",
"Right before Spoon configuration of transformation to be executed takes place" ),
JobStart( "JobStart", "A job starts" ),
JobHeartbeat( "JobHeartbeat", "A signal sent at regular intervals to indicate that the job is still active" ),
JobFinish( "JobFinish", "A job finishes" ),
JobBeforeJobEntryExecution( "JobBeforeJobEntryExecution", "Before a job entry executes" ),
JobAfterJobEntryExecution( "JobAfterJobEntryExecution", "After a job entry executes" ),
JobBeginProcessing( "JobBeginProcessing", "Start of a job at the end of the log table handling" ),
JobPainterArrow( "JobPainterArrow", "Draw additional information on top of a job hop (arrow)" ),
JobPainterJobEntry( "TransPainterJobEntry", "Draw additional information on top of a job entry copy icon" ),
JobPainterStart( "JobPainterStart", "Draw job or plugin metadata at the start (below the rest)" ),
JobPainterEnd( "JobPainterEnd", "Draw job or plugin metadata at the end (on top of all the rest)" ),
JobGraphMouseDown( "JobGraphMouseDown", "A left or right button was clicked in a job" ),
JobBeforeOpen( "JobBeforeOpen", "A job file is about to be opened" ),
JobAfterOpen( "JobAfterOpen", "A job file was opened" ),
JobBeforeSave( "JobBeforeSave", "A job file is about to be saved" ),
JobAfterSave( "JobAfterSave", "A job file was saved" ),
JobBeforeClose( "JobBeforeClose", "A job file is about to be closed" ),
JobAfterClose( "JobAfterClose", "A job file was closed" ),
JobChanged( "JobChanged", "A job has been changed" ),
JobGraphMouseDoubleClick( "JobGraphMouseDoubleClick",
"A left or right button was double-clicked in a job" ),
JobGraphJobEntrySetMenu( "JobGraphJobEntrySetMenu", "Manipulate the menu on right click on a job entry" ),
JobDialogShowRetrieveLogTableFields( "JobDialogShowRetrieveLogTableFields",
"Show or retrieve the contents of the fields of a log channel on the log channel composite" ),
JobMetaLoaded( "JobMetaLoaded", "Job metadata was loaded" ),
SpoonJobMetaExecutionStart( "SpoonJobMetaExecutionStart", "Spoon initiates the execution of a job (JobMeta)" ),
SpoonJobExecutionConfiguration( "SpoonJobExecutionConfiguration",
"Right before Spoon configuration of job to be executed takes place" ),
DatabaseConnected( "DatabaseConnected", "A connection to a database was made" ),
DatabaseDisconnected( "DatabaseDisconnected", "A connection to a database was terminated" ),
StepBeforeInitialize( "StepBeforeInitialize", "Right before a step is about to be initialized" ),
StepAfterInitialize( "StepAfterInitialize", "After a step is initialized" ),
StepBeforeStart( "StepBeforeStart", "Right before a step is about to be started" ),
StepFinished( "StepFinished", "After a step has finished" ),
BeforeCheckSteps( "BeforeCheckSteps", "Right before a set of steps is about to be verified." ),
AfterCheckSteps( "AfterCheckSteps", "After a set of steps has been checked for warnings/errors." ),
BeforeCheckStep( "BeforeCheckStep", "Right before a step is about to be verified." ),
AfterCheckStep( "AfterCheckStep", "After a step has been checked for warnings/errors." ),
CarteStartup( "CarteStartup", "Right after the Carte webserver has started and is fully functional" ),
CarteShutdown( "CarteShutdown", "Right before the Carte webserver will shut down" ),
SpoonViewTreeExtension ( "SpoonViewTreeExtension" , "View tree spoon extension" ),
SpoonPopupMenuExtension ( "SpoonPopupMenuExtension" , "Pop up menu extension for the view tree" ),
SpoonTreeDelegateExtension ( "SpoonTreeDelegateExtension" , "During the SpoonTreeDelegate execution" ),
AfterDeleteRepositoryObject( "AfterDeleteRepositoryObject",
"After an object has been deleted from the repository" );
public String id;
public String description;
private KettleExtensionPoint( String id, String description ) {
this.id = id;
this.description = description;
}
}
| mattyb149/pentaho-kettle | core/src/org/pentaho/di/core/extension/KettleExtensionPoint.java | Java | apache-2.0 | 7,249 |
/**
* $RCSfile$
* $Revision: 19238 $
* $Date: 2005-07-07 09:53:37 -0700 (Thu, 07 Jul 2005) $
*
* Copyright (C) 1999-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.xmpp.workgroup.event;
import org.jivesoftware.xmpp.workgroup.AgentSession;
import org.jivesoftware.xmpp.workgroup.Workgroup;
/**
* An abstract adapter class for receiving workgroup events. The methods in this class
* are empty -- in other words, this class exists as a convenience for creating listener
* objects.<p>
*
* Workgroup Events let you track when a workgroup is destroyed, created, modified, or when a
* support chat has been created and ended.<p>
*
* Extend this class to create a listener and override the methods for the events of interest.
* Create a listener object using the extended class and then register it with
* a WorkgroupEventDispatcher using the
* {@link WorkgroupEventDispatcher#addListener(WorkgroupEventListener) addListener} method.
*
* @author Derek DeMoro
* @see WorkgroupEventListener
* @see WorkgroupEventDispatcher
*/
public abstract class WorkgroupEventAdapter implements WorkgroupEventListener {
public void workgroupCreated(Workgroup workgroup) {
}
public void workgroupDeleting(Workgroup workgroup) {
}
public void workgroupDeleted(Workgroup workgroup) {
}
public void workgroupOpened(Workgroup workgroup) {
}
public void workgroupClosed(Workgroup workgroup) {
}
public void agentJoined(Workgroup workgroup, AgentSession agentSession) {
}
public void agentDeparted(Workgroup workgroup, AgentSession agentSession) {
}
public void chatSupportStarted(Workgroup workgroup, String sessionID) {
}
public void chatSupportFinished(Workgroup workgroup, String sessionID) {
}
public void agentJoinedChatSupport(Workgroup workgroup, String sessionID, AgentSession agentSession) {
}
public void agentLeftChatSupport(Workgroup workgroup, String sessionID, AgentSession agentSession) {
}
}
| fanjunwei/openfireSSO | src/plugins/fastpath/src/java/org/jivesoftware/xmpp/workgroup/event/WorkgroupEventAdapter.java | Java | apache-2.0 | 2,681 |
// Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.pantsbuild.testproject.aliases;
/**
* Part of an integration test to ensure that target aliases are replaced by their dependencies in
* the build graph.
*
* See tests/python/pants_test/core_tasks/test_substitute_target_aliases_integration.py
*/
public class UseIntransitiveDependency {
public static void main(String[] args) {
System.out.println("Managed to run this class.");
}
/**
* We don't attempt to reference this, because this will assuredly fail at run-time. We just want
* to make sure this reference is here at compile-time.
*/
public static void referenceIntransitive() {
new IntransitiveDependency();
}
}
| UnrememberMe/pants | testprojects/src/java/org/pantsbuild/testproject/aliases/UseIntransitiveDependency.java | Java | apache-2.0 | 798 |
package me.grantland.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build;
import android.text.Editable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.SingleLineTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
/**
* A helper class to enable automatically resizing {@link TextView}`s {@code textSize} to fit
* within its bounds.
*
* @attr ref R.styleable.AutofitTextView_sizeToFit
* @attr ref R.styleable.AutofitTextView_minTextSize
* @attr ref R.styleable.AutofitTextView_precision
*/
public class AutofitHelper {
private static final String TAG = "AutoFitTextHelper";
private static final boolean SPEW = false;
// Minimum size of the text in pixels
private static final int DEFAULT_MIN_TEXT_SIZE = 8; //sp
// How precise we want to be when reaching the target textWidth size
private static final float DEFAULT_PRECISION = 0.5f;
/**
* Creates a new instance of {@code AutofitHelper} that wraps a {@link TextView} and enables
* automatically sizing the text to fit.
*/
public static AutofitHelper create(TextView view) {
return create(view, null, 0);
}
/**
* Creates a new instance of {@code AutofitHelper} that wraps a {@link TextView} and enables
* automatically sizing the text to fit.
*/
public static AutofitHelper create(TextView view, AttributeSet attrs) {
return create(view, attrs, 0);
}
/**
* Creates a new instance of {@code AutofitHelper} that wraps a {@link TextView} and enables
* automatically sizing the text to fit.
*/
public static AutofitHelper create(TextView view, AttributeSet attrs, int defStyle) {
AutofitHelper helper = new AutofitHelper(view);
boolean sizeToFit = true;
if (attrs != null) {
Context context = view.getContext();
int minTextSize = (int) helper.getMinTextSize();
float precision = helper.getPrecision();
TypedArray ta = context.obtainStyledAttributes(
attrs,
R.styleable.AutofitTextView,
defStyle,
0);
sizeToFit = ta.getBoolean(R.styleable.AutofitTextView_sizeToFit, sizeToFit);
minTextSize = ta.getDimensionPixelSize(R.styleable.AutofitTextView_minTextSize,
minTextSize);
precision = ta.getFloat(R.styleable.AutofitTextView_precision, precision);
ta.recycle();
helper.setMinTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
.setPrecision(precision);
}
helper.setEnabled(sizeToFit);
return helper;
}
/**
* Re-sizes the textSize of the TextView so that the text fits within the bounds of the View.
*/
private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize,
int maxLines, float precision) {
if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) {
// Don't auto-size since there's no limit on lines.
return;
}
int targetWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();
if (targetWidth <= 0) {
return;
}
CharSequence text = view.getText();
TransformationMethod method = view.getTransformationMethod();
if (method != null) {
text = method.getTransformation(text, view);
}
Context context = view.getContext();
Resources r = Resources.getSystem();
DisplayMetrics displayMetrics;
float size = maxTextSize;
float high = size;
float low = 0;
if (context != null) {
r = context.getResources();
}
displayMetrics = r.getDisplayMetrics();
paint.set(view.getPaint());
paint.setTextSize(size);
if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
|| getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines) {
size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
displayMetrics);
}
if (size < minTextSize) {
size = minTextSize;
}
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}
/**
* Recursive binary search to find the best size for the text.
*/
private static float getAutofitTextSize(CharSequence text, TextPaint paint,
float targetWidth, int maxLines, float low, float high, float precision,
DisplayMetrics displayMetrics) {
float mid = (low + high) / 2.0f;
int lineCount = 1;
StaticLayout layout = null;
paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid,
displayMetrics));
if (maxLines != 1) {
layout = new StaticLayout(text, paint, (int)targetWidth, Layout.Alignment.ALIGN_NORMAL,
1.0f, 0.0f, true);
lineCount = layout.getLineCount();
}
if (SPEW) Log.d(TAG, "low=" + low + " high=" + high + " mid=" + mid +
" target=" + targetWidth + " maxLines=" + maxLines + " lineCount=" + lineCount);
if (lineCount > maxLines) {
// For the case that `text` has more newline characters than `maxLines`.
if ((high - low) < precision) {
return low;
}
return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision,
displayMetrics);
}
else if (lineCount < maxLines) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision,
displayMetrics);
}
else {
float maxLineWidth = 0;
if (maxLines == 1) {
maxLineWidth = paint.measureText(text, 0, text.length());
} else {
for (int i = 0; i < lineCount; i++) {
if (layout.getLineWidth(i) > maxLineWidth) {
maxLineWidth = layout.getLineWidth(i);
}
}
}
if ((high - low) < precision) {
return low;
} else if (maxLineWidth > targetWidth) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, low, mid, precision,
displayMetrics);
} else if (maxLineWidth < targetWidth) {
return getAutofitTextSize(text, paint, targetWidth, maxLines, mid, high, precision,
displayMetrics);
} else {
return mid;
}
}
}
private static int getLineCount(CharSequence text, TextPaint paint, float size, float width,
DisplayMetrics displayMetrics) {
paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size,
displayMetrics));
StaticLayout layout = new StaticLayout(text, paint, (int)width,
Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
return layout.getLineCount();
}
private static int getMaxLines(TextView view) {
int maxLines = -1; // No limit (Integer.MAX_VALUE also means no limit)
TransformationMethod method = view.getTransformationMethod();
if (method != null && method instanceof SingleLineTransformationMethod) {
maxLines = 1;
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// setMaxLines() and getMaxLines() are only available on android-16+
maxLines = view.getMaxLines();
}
return maxLines;
}
// Attributes
private TextView mTextView;
private TextPaint mPaint;
/**
* Original textSize of the TextView.
*/
private float mTextSize;
private int mMaxLines;
private float mMinTextSize;
private float mMaxTextSize;
private float mPrecision;
private boolean mEnabled;
private boolean mIsAutofitting;
private ArrayList<OnTextSizeChangeListener> mListeners;
private TextWatcher mTextWatcher = new AutofitTextWatcher();
private View.OnLayoutChangeListener mOnLayoutChangeListener =
new AutofitOnLayoutChangeListener();
private AutofitHelper(TextView view) {
final Context context = view.getContext();
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mTextView = view;
mPaint = new TextPaint();
setRawTextSize(view.getTextSize());
mMaxLines = getMaxLines(view);
mMinTextSize = scaledDensity * DEFAULT_MIN_TEXT_SIZE;
mMaxTextSize = mTextSize;
mPrecision = DEFAULT_PRECISION;
}
/**
* Adds an {@link OnTextSizeChangeListener} to the list of those whose methods are called
* whenever the {@link TextView}'s {@code textSize} changes.
*/
public AutofitHelper addOnTextSizeChangeListener(OnTextSizeChangeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<OnTextSizeChangeListener>();
}
mListeners.add(listener);
return this;
}
/**
* Removes the specified {@link OnTextSizeChangeListener} from the list of those whose methods
* are called whenever the {@link TextView}'s {@code textSize} changes.
*/
public AutofitHelper removeOnTextSizeChangeListener(OnTextSizeChangeListener listener) {
if (mListeners != null) {
mListeners.remove(listener);
}
return this;
}
/**
* Returns the amount of precision used to calculate the correct text size to fit within its
* bounds.
*/
public float getPrecision() {
return mPrecision;
}
/**
* Set the amount of precision used to calculate the correct text size to fit within its
* bounds. Lower precision is more precise and takes more time.
*
* @param precision The amount of precision.
*/
public AutofitHelper setPrecision(float precision) {
if (mPrecision != precision) {
mPrecision = precision;
autofit();
}
return this;
}
/**
* Returns the minimum size (in pixels) of the text.
*/
public float getMinTextSize() {
return mMinTextSize;
}
/**
* Set the minimum text size to the given value, interpreted as "scaled pixel" units. This size
* is adjusted based on the current density and user font size preference.
*
* @param size The scaled pixel size.
*
* @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize
*/
public AutofitHelper setMinTextSize(float size) {
return setMinTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
/**
* Set the minimum text size to a given unit and value. See TypedValue for the possible
* dimension units.
*
* @param unit The desired dimension unit.
* @param size The desired size in the given units.
*
* @attr ref me.grantland.R.styleable#AutofitTextView_minTextSize
*/
public AutofitHelper setMinTextSize(int unit, float size) {
Context context = mTextView.getContext();
Resources r = Resources.getSystem();
if (context != null) {
r = context.getResources();
}
setRawMinTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics()));
return this;
}
private void setRawMinTextSize(float size) {
if (size != mMinTextSize) {
mMinTextSize = size;
autofit();
}
}
/**
* Returns the maximum size (in pixels) of the text.
*/
public float getMaxTextSize() {
return mMaxTextSize;
}
/**
* Set the maximum text size to the given value, interpreted as "scaled pixel" units. This size
* is adjusted based on the current density and user font size preference.
*
* @param size The scaled pixel size.
*
* @attr ref android.R.styleable#TextView_textSize
*/
public AutofitHelper setMaxTextSize(float size) {
return setMaxTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
/**
* Set the maximum text size to a given unit and value. See TypedValue for the possible
* dimension units.
*
* @param unit The desired dimension unit.
* @param size The desired size in the given units.
*
* @attr ref android.R.styleable#TextView_textSize
*/
public AutofitHelper setMaxTextSize(int unit, float size) {
Context context = mTextView.getContext();
Resources r = Resources.getSystem();
if (context != null) {
r = context.getResources();
}
setRawMaxTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics()));
return this;
}
private void setRawMaxTextSize(float size) {
if (size != mMaxTextSize) {
mMaxTextSize = size;
autofit();
}
}
/**
* @see TextView#getMaxLines()
*/
public int getMaxLines() {
return mMaxLines;
}
/**
* @see TextView#setMaxLines(int)
*/
public AutofitHelper setMaxLines(int lines) {
if (mMaxLines != lines) {
mMaxLines = lines;
autofit();
}
return this;
}
/**
* Returns whether or not automatically resizing text is enabled.
*/
public boolean isEnabled() {
return mEnabled;
}
/**
* Set the enabled state of automatically resizing text.
*/
public AutofitHelper setEnabled(boolean enabled) {
if (mEnabled != enabled) {
mEnabled = enabled;
if (enabled) {
mTextView.addTextChangedListener(mTextWatcher);
mTextView.addOnLayoutChangeListener(mOnLayoutChangeListener);
autofit();
} else {
mTextView.removeTextChangedListener(mTextWatcher);
mTextView.removeOnLayoutChangeListener(mOnLayoutChangeListener);
mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
}
}
return this;
}
/**
* Returns the original text size of the View.
*
* @see TextView#getTextSize()
*/
public float getTextSize() {
return mTextSize;
}
/**
* Set the original text size of the View.
*
* @see TextView#setTextSize(float)
*/
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
/**
* Set the original text size of the View.
*
* @see TextView#setTextSize(int, float)
*/
public void setTextSize(int unit, float size) {
if (mIsAutofitting) {
// We don't want to update the TextView's actual textSize while we're autofitting
// since it'd get set to the autofitTextSize
return;
}
Context context = mTextView.getContext();
Resources r = Resources.getSystem();
if (context != null) {
r = context.getResources();
}
setRawTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics()));
}
private void setRawTextSize(float size) {
if (mTextSize != size) {
mTextSize = size;
}
}
private void autofit() {
float oldTextSize = mTextView.getTextSize();
float textSize;
mIsAutofitting = true;
autofit(mTextView, mPaint, mMinTextSize, mMaxTextSize, mMaxLines, mPrecision);
mIsAutofitting = false;
textSize = mTextView.getTextSize();
if (textSize != oldTextSize) {
sendTextSizeChange(textSize, oldTextSize);
}
}
private void sendTextSizeChange(float textSize, float oldTextSize) {
if (mListeners == null) {
return;
}
for (OnTextSizeChangeListener listener : mListeners) {
listener.onTextSizeChange(textSize, oldTextSize);
}
}
private class AutofitTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
// do nothing
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
autofit();
}
@Override
public void afterTextChanged(Editable editable) {
// do nothing
}
}
private class AutofitOnLayoutChangeListener implements View.OnLayoutChangeListener {
@Override
public void onLayoutChange(View view, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
autofit();
}
}
/**
* When an object of a type is attached to an {@code AutofitHelper}, its methods will be called
* when the {@code textSize} is changed.
*/
public interface OnTextSizeChangeListener {
/**
* This method is called to notify you that the size of the text has changed to
* {@code textSize} from {@code oldTextSize}.
*/
public void onTextSizeChange(float textSize, float oldTextSize);
}
}
| Tengio/android-autofittextview | library/src/main/java/me/grantland/widget/AutofitHelper.java | Java | apache-2.0 | 17,822 |
/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */
/* JavaCCOptions: */
package org.apache.lucene.queryparser.flexible.standard.parser;
/** Token Manager Error. */
public class TokenMgrError extends Error
{
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/*
* Ordinals for various reasons why an Error of this type can be thrown.
*/
/**
* Lexical error occurred.
*/
static final int LEXICAL_ERROR = 0;
/**
* An attempt was made to create a second instance of a static token manager.
*/
static final int STATIC_LEXER_ERROR = 1;
/**
* Tried to change to an invalid lexical state.
*/
static final int INVALID_LEXICAL_STATE = 2;
/**
* Detected (and bailed out of) an infinite loop in the token manager.
*/
static final int LOOP_DETECTED = 3;
/**
* Indicates the reason why the exception is thrown. It will have
* one of the above 4 values.
*/
int errorCode;
/**
* Replaces unprintable characters by their escaped (or unicode escaped)
* equivalents in the given string
*/
protected static final String addEscapes(String str) {
StringBuilder retval = new StringBuilder();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
/**
* Returns a detailed message for the Error when it is thrown by the
* token manager to indicate a lexical error.
* Parameters :
* EOFSeen : indicates if EOF caused the lexical error
* curLexState : lexical state in which this error occurred
* errorLine : line number when the error occurred
* errorColumn : column number when the error occurred
* errorAfter : prefix that was seen before this error occurred
* curchar : the offending character
* Note: You can customize the lexical error message by modifying this method.
*/
protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
return("Lexical error at line " +
errorLine + ", column " +
errorColumn + ". Encountered: " +
(EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
"after : \"" + addEscapes(errorAfter) + "\"");
}
/**
* You can also modify the body of this method to customize your error messages.
* For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
* of end-users concern, so you can return something like :
*
* "Internal Error : Please file a bug report .... "
*
* from this method for such cases in the release version of your parser.
*/
public String getMessage() {
return super.getMessage();
}
/*
* Constructors of various flavors follow.
*/
/** No arg constructor. */
public TokenMgrError() {
}
/** Constructor with message and reason. */
public TokenMgrError(String message, int reason) {
super(message);
errorCode = reason;
}
/** Full Constructor. */
public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
}
}
/* JavaCC - OriginalChecksum=3ca7fbf7de9f2424b131a5499b0a78d0 (do not edit this line) */
| smartan/lucene | src/main/java/org/apache/lucene/queryparser/flexible/standard/parser/TokenMgrError.java | Java | apache-2.0 | 4,466 |
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of 'LWJGL' 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 org.lwjgl.util.generator.opengl;
/**
*
* @author elias_naur <[email protected]>
* @version $Revision: 2983 $
* $Id: GLdouble.java 2983 2008-04-07 18:36:09Z matzon $
*/
import org.lwjgl.util.generator.NativeType;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@NativeType
@Target({ElementType.PARAMETER, ElementType.METHOD})
public @interface GLdouble {
}
| andrewmcvearry/mille-bean | lwjgl/src/java/org/lwjgl/util/generator/opengl/GLdouble.java | Java | mit | 2,036 |
package com.mariussoft.endlessjabber.sdk;
import android.content.Context;
/**
*
* Interface to implement EndlessJabber integration
*
*/
public interface IEndlessJabberImplementation {
/**
* Update all messages in the SMS/MMS repositories as read where the time <= the provided time as well as where the threadID matches the provided ID
* @param context The context to utilize
* @param time The 'time' in the SMS database to use when marking messages as read
* (NOTE* for MMS divide by 1000 as MMS repository stores times as 1/1000th of the SMS)
* @param threadID The ID of the thread in the SMS/MMS repositories to update
*/
void UpdateReadMessages(Context context, long time, int threadID);
/**
* Delete any messages/conversations in the SMS/MMS repositories where the threadID matches the provided ID
* @param context The context to utilize
* @param threadID The ID of the thread in the SMS/MMS repositories to delete
*/
void DeleteThread(Context context,int threadID);
/**
* Method gets called when EndlessJabber is requested to send an MMS message via the web app
* @param context The context to utilize
* @param recipients List of recipients to send message to
* @param parts The message parts to send along with message
* @param subject The MMS subject of the message
* @param save Whether or not to save the MMS to the MMS repository
* @param send If true, send the message along with saving it to the MMS repository
* NOTE: On KitKat save will be true only when enabled in the SDK & your app is the default messaging app on the system
*
* If both save & send are false, this call is only for informational purposes (e.g. modify notifications, update UI, etc...)
*/
void SendMMS(Context context, String[] recipients, MMSPart[] parts, String subject, boolean save, boolean send);
/**
* Method gets called when EndlessJabber is requested to send an SMS message via the web app
* @param context The context to utilize
* @param recipients List of recipients to send message to
* @param message The message to send
* @param send If true, send the message along with saving it to the SMS repository, otherwise this is only for informational purposes (e.g. modify notifications, update UI, etc...)
*/
void SendSMS(Context context, String[] recipients, String message, boolean send);
}
| AdeebNqo/Thula | Thula/src/main/java/com/mariussoft/endlessjabber/sdk/IEndlessJabberImplementation.java | Java | gpl-3.0 | 2,381 |
/**
* <a href="https://github.com/b3log/solo">Solo</a>.
*/
package org.b3log.solo;
| 446541492/solo | src/main/java/org/b3log/solo/package-info.java | Java | apache-2.0 | 89 |
/**
* 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.storm.container.cgroup.core;
import org.apache.storm.container.cgroup.CgroupUtils;
import org.apache.storm.container.cgroup.SubSystemType;
import org.apache.storm.container.cgroup.Device;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
public class DevicesCore implements CgroupCore {
private final String dir;
private static final String DEVICES_ALLOW = "/devices.allow";
private static final String DEVICES_DENY = "/devices.deny";
private static final String DEVICES_LIST = "/devices.list";
private static final char TYPE_ALL = 'a';
private static final char TYPE_BLOCK = 'b';
private static final char TYPE_CHAR = 'c';
private static final int ACCESS_READ = 1;
private static final int ACCESS_WRITE = 2;
private static final int ACCESS_CREATE = 4;
private static final char ACCESS_READ_CH = 'r';
private static final char ACCESS_WRITE_CH = 'w';
private static final char ACCESS_CREATE_CH = 'm';
private static final Logger LOG = LoggerFactory.getLogger(DevicesCore.class);
public DevicesCore(String dir) {
this.dir = dir;
}
@Override
public SubSystemType getType() {
return SubSystemType.devices;
}
public static class Record {
Device device;
char type;
int accesses;
public Record(char type, Device device, int accesses) {
this.type = type;
this.device = device;
this.accesses = accesses;
}
public Record(String output) {
if (output.contains("*")) {
LOG.debug("Pre: {}", output);
output = output.replaceAll("\\*", "-1");
LOG.debug("After: {}",output);
}
String[] splits = output.split("[: ]");
type = splits[0].charAt(0);
int major = Integer.parseInt(splits[1]);
int minor = Integer.parseInt(splits[2]);
device = new Device(major, minor);
accesses = 0;
for (char c : splits[3].toCharArray()) {
if (c == ACCESS_READ_CH) {
accesses |= ACCESS_READ;
}
if (c == ACCESS_CREATE_CH) {
accesses |= ACCESS_CREATE;
}
if (c == ACCESS_WRITE_CH) {
accesses |= ACCESS_WRITE;
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(type);
sb.append(' ');
sb.append(device.major);
sb.append(':');
sb.append(device.minor);
sb.append(' ');
sb.append(getAccessesFlag(accesses));
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + accesses;
result = prime * result + ((device == null) ? 0 : device.hashCode());
result = prime * result + type;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Record other = (Record) obj;
if (accesses != other.accesses) {
return false;
}
if (device == null) {
if (other.device != null) {
return false;
}
} else if (!device.equals(other.device)) {
return false;
}
if (type != other.type) {
return false;
}
return true;
}
public static Record[] parseRecordList(List<String> output) {
Record[] records = new Record[output.size()];
for (int i = 0, l = output.size(); i < l; i++) {
records[i] = new Record(output.get(i));
}
return records;
}
public static StringBuilder getAccessesFlag(int accesses) {
StringBuilder sb = new StringBuilder();
if ((accesses & ACCESS_READ) != 0) {
sb.append(ACCESS_READ_CH);
}
if ((accesses & ACCESS_WRITE) != 0) {
sb.append(ACCESS_WRITE_CH);
}
if ((accesses & ACCESS_CREATE) != 0) {
sb.append(ACCESS_CREATE_CH);
}
return sb;
}
}
private void setPermission(String prop, char type, Device device, int accesses) throws IOException {
Record record = new Record(type, device, accesses);
CgroupUtils.writeFileByLine(CgroupUtils.getDir(this.dir, prop), record.toString());
}
public void setAllow(char type, Device device, int accesses) throws IOException {
setPermission(DEVICES_ALLOW, type, device, accesses);
}
public void setDeny(char type, Device device, int accesses) throws IOException {
setPermission(DEVICES_DENY, type, device, accesses);
}
public Record[] getList() throws IOException {
List<String> output = CgroupUtils.readFileByLine(CgroupUtils.getDir(this.dir, DEVICES_LIST));
return Record.parseRecordList(output);
}
}
| kamleshbhatt/storm | storm-client/src/jvm/org/apache/storm/container/cgroup/core/DevicesCore.java | Java | apache-2.0 | 6,335 |
/*
* Copyright (c) 2004 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.infer.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Mutable {}
| raphaelamorim/infer | infer/annotations/com/facebook/infer/annotation/Mutable.java | Java | bsd-3-clause | 660 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.bridge;
import java.io.IOException;
import java.io.StringWriter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
public class JavaScriptModuleConfigTest {
private static interface SomeModule extends JavaScriptModule {
public void stringMethod(String arg);
public void intMethod(int arg);
}
private static interface OtherModule extends JavaScriptModule {
public void method(String arg1, int arg2);
}
@Test
public void testModuleWithMethods() throws Exception {
JavaScriptModulesConfig jsModulesConfig = new JavaScriptModulesConfig.Builder()
.add(SomeModule.class)
.build();
String json = getModuleDescriptions(jsModulesConfig);
JsonNode node = parse(json);
assertThat(node).hasSize(1);
JsonNode module = node.fields().next().getValue();
assertThat(module).isNotNull();
JsonNode methods = module.get("methods");
assertThat(methods)
.isNotNull()
.hasSize(2);
JsonNode intMethodNode = methods.get("intMethod");
assertThat(intMethodNode).isNotNull();
assertThat(intMethodNode.get("methodID").asInt()).isEqualTo(0);
JsonNode stringMethod = methods.get("stringMethod");
assertThat(stringMethod).isNotNull();
assertThat(stringMethod.get("methodID").asInt()).isEqualTo(1);
}
@Test
public void testMultipleModules() throws Exception {
JavaScriptModulesConfig jsModulesConfig = new JavaScriptModulesConfig.Builder()
.add(OtherModule.class)
.add(SomeModule.class)
.build();
String json = getModuleDescriptions(jsModulesConfig);
JsonNode node = parse(json);
assertThat(node).hasSize(2);
JsonNode someModuleNode = node.get("SomeModule");
assertThat(someModuleNode).isNotNull();
int someModuleID = someModuleNode.get("moduleID").asInt();
JsonNode otherModuleNode = node.get("OtherModule");
assertThat(otherModuleNode).isNotNull();
int otherModuleID = otherModuleNode.get("moduleID").asInt();
assertThat(otherModuleID)
.isNotEqualTo(someModuleID);
}
private static String getModuleDescriptions(JavaScriptModulesConfig jsModulesConfig)
throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
jsModulesConfig.writeModuleDescriptions(writer);
writer.close();
return stringWriter.getBuffer().toString();
}
private JsonNode parse(String json) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(json);
}
}
| bohanapp/PropertyFinder | node_modules/react-native/ReactAndroid/src/test/java/com/facebook/react/bridge/JavaScriptModuleConfigTest.java | Java | mit | 3,010 |
package com.raizlabs.android.dbflow.test.list;
import com.raizlabs.android.dbflow.annotation.Database;
/**
* Description:
*/
@Database(version = 1, name = ListDatabase.NAME)
public class ListDatabase {
public static final String NAME = "List";
}
| omegasoft7/DBFlow | library/src/androidTest/java/com/raizlabs/android/dbflow/test/list/ListDatabase.java | Java | mit | 255 |
/**
* 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 com.datatorrent.stram.api;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.Operator;
import com.datatorrent.api.StatsListener;
import com.datatorrent.stram.plan.logical.LogicalPlanConfiguration;
/**
* <p>StramToNodeChangeLoggersRequest class.</p>
*
* @since 1.0.4
*/
public class StramToNodeSetPropertyRequest extends StreamingContainerUmbilicalProtocol.StramToNodeRequest implements Serializable
{
private String propertyKey;
private String propertyValue;
public StramToNodeSetPropertyRequest()
{
requestType = RequestType.CUSTOM;
cmd = new SetPropertyRequest();
}
public String getPropertyKey()
{
return propertyKey;
}
public void setPropertyKey(String propertyKey)
{
this.propertyKey = propertyKey;
}
public String getPropertyValue()
{
return propertyValue;
}
public void setPropertyValue(String propertyValue)
{
this.propertyValue = propertyValue;
}
private static final long serialVersionUID = 201405271034L;
private static final Logger logger = LoggerFactory.getLogger(StramToNodeSetPropertyRequest.class);
private class SetPropertyRequest implements StatsListener.OperatorRequest, Serializable
{
@Override
public StatsListener.OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException
{
final Map<String, String> properties = Collections.singletonMap(propertyKey, propertyValue);
logger.info("Setting property {} on operator {}", properties, operator);
LogicalPlanConfiguration.setOperatorProperties(operator, properties);
return null;
}
@Override
public String toString()
{
return "Set Property";
}
}
}
| apache/incubator-apex-core | engine/src/main/java/com/datatorrent/stram/api/StramToNodeSetPropertyRequest.java | Java | apache-2.0 | 2,657 |
/*
* Copyright (c) 2013, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oauth.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException;
import org.wso2.carbon.identity.oauth.Parameters;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor;
import org.wso2.carbon.identity.oauth.tokenprocessor.TokenPersistenceProcessor;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class OAuthConsumerDAO {
public static final Log log = LogFactory.getLog(OAuthConsumerDAO.class);
private TokenPersistenceProcessor persistenceProcessor;
public OAuthConsumerDAO() {
try {
persistenceProcessor = OAuthServerConfiguration.getInstance().getPersistenceProcessor();
} catch (IdentityOAuth2Exception e) {
log.error("Error retrieving TokenPersistenceProcessor. Defaulting to PlainTextProcessor", e);
persistenceProcessor = new PlainTextPersistenceProcessor();
}
}
/**
* Returns the consumer secret corresponding to a given consumer key
*
* @param consumerKey Consumer key
* @return consumer secret
* @throws IdentityOAuthAdminException Error when reading consumer secret from the persistence store
*/
public String getOAuthConsumerSecret(String consumerKey) throws IdentityOAuthAdminException {
String consumerSecret = null;
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_CONSUMER_SECRET);
prepStmt.setString(1, persistenceProcessor.getProcessedClientId(consumerKey));
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
consumerSecret = persistenceProcessor.getPreprocessedClientSecret(resultSet.getString(1));
} else {
if(log.isDebugEnabled()) {
log.debug("Invalid Consumer Key : " + consumerKey);
}
}
connection.commit();
} catch (SQLException e) {
throw new IdentityOAuthAdminException("Error when reading the consumer secret for consumer key : " +
consumerKey, e);
} catch (IdentityOAuth2Exception e) {
throw new IdentityOAuthAdminException("Error occurred while processing client id and client secret by " +
"TokenPersistenceProcessor", e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return consumerSecret;
}
/**
* Returns the username corresponding to a given client id and consumer secret
*
* @param clientId Client Id/Key
* @param clientSecret Consumer secret
* @return Username if successful, empty string otherwise
* @throws IdentityOAuthAdminException Error when reading consumer secret from the persistence store
*/
public String getAuthenticatedUsername(String clientId, String clientSecret) throws IdentityOAuthAdminException {
String username = "";
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_USERNAME_FOR_KEY_AND_SECRET);
prepStmt.setString(1, clientId);
prepStmt.setString(2, clientSecret);
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
username = resultSet.getString(1);
} else {
log.debug("Invalid client id : " + clientId + ", and consumer secret : " + clientSecret);
}
connection.commit();
} catch (SQLException e) {
log.error("Error when executing the SQL : " + SQLQueries.OAuthConsumerDAOSQLQueries.GET_USERNAME_FOR_KEY_AND_SECRET);
log.error(e.getMessage(), e);
throw new IdentityOAuthAdminException("Error while reading username for client id : " + clientId +
", and consumer secret : " + clientSecret);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return username;
}
/**
* Get the token secret for the given access token
*
* @param token OAuth token, this could be a request token(temporary token) or a access token
* @param isAccessToken True, if it is as access token
* @return Token Secret
* @throws IdentityOAuthAdminException Error when accessing the token secret from the persistence store.
*/
public String getOAuthTokenSecret(String token, Boolean isAccessToken) throws IdentityException {
String tokenSecret = null;
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
String sqlStmt;
if (isAccessToken) {
sqlStmt = SQLQueries.OAuthConsumerDAOSQLQueries.GET_ACCESS_TOKEN_SECRET;
} else {
sqlStmt = SQLQueries.OAuthConsumerDAOSQLQueries.GET_REQ_TOKEN_SECRET;
}
try {
prepStmt = connection.prepareStatement(sqlStmt);
prepStmt.setString(1, token);
resultSet = prepStmt.executeQuery();
connection.commit();
if (resultSet.next()) {
tokenSecret = resultSet.getString(1);
} else {
throw new IdentityException("Invalid token : " + token);
}
} catch (SQLException e) {
throw new IdentityOAuthAdminException("Error when reading the token secret for token : " +
token, e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return tokenSecret;
}
/**
* Creates a new OAuth token.
*
* @param consumerKey Consumer Key
* @param oauthToken OAuth Token, a unique identifier
* @param oauthSecret OAuth Secret
* @param userCallback Where the user should be redirected once the approval completed.
* @param scope Resource or the scope of the resource.
* @throws IdentityOAuthAdminException Error when writing the OAuth Req. token to the persistence store
*/
public void createOAuthRequestToken(String consumerKey, String oauthToken, String oauthSecret,
String userCallback, String scope) throws IdentityOAuthAdminException {
final String OUT_OF_BAND = "oob";
if (userCallback == null || OUT_OF_BAND.equals(userCallback)) {
userCallback = getCallbackURLOfApp(consumerKey);
}
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.ADD_OAUTH_REQ_TOKEN);
prepStmt.setString(1, oauthToken);
prepStmt.setString(2, oauthSecret);
prepStmt.setString(3, userCallback);
prepStmt.setString(4, scope);
prepStmt.setString(5, Boolean.toString(false));
prepStmt.setString(6, consumerKey);
prepStmt.execute();
connection.commit();
} catch (SQLException e) {
log.error("Error when executing the SQL : " + SQLQueries.OAuthConsumerDAOSQLQueries.ADD_OAUTH_REQ_TOKEN);
log.error(e.getMessage(), e);
throw new IdentityOAuthAdminException("Error when creating the request token for consumer : " + consumerKey);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
}
}
/**
* Authorizes the OAuth request token.
*
* @param oauthToken Authorized OAuth token
* @param userName The name of the user who authorized the token.
* @param oauthVerifier oauth_verifier - an unique identifier
* @throws IdentityException
*/
public Parameters authorizeOAuthToken(String oauthToken, String userName, String oauthVerifier)
throws IdentityException {
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.AUTHORIZE_REQ_TOKEN);
prepStmt.setString(1, Boolean.toString(true));
prepStmt.setString(2, oauthVerifier);
prepStmt.setString(3, userName);
prepStmt.setString(4, oauthToken);
prepStmt.execute();
connection.commit();
} catch (SQLException e) {
throw new IdentityOAuthAdminException("Error when authorizing the request token : " + oauthToken);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
}
Parameters params = new Parameters();
params.setOauthCallback(getCallbackURLOfReqToken(oauthToken));
return params;
}
public Parameters getRequestToken(String oauthToken) throws IdentityException {
Parameters params = new Parameters();
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_REQ_TOKEN);
prepStmt.setString(1, oauthToken);
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
params.setOauthToken(resultSet.getString(1));
params.setOauthTokenSecret(resultSet.getString(2));
params.setOauthConsumerKey(resultSet.getString(3));
params.setOauthCallback(resultSet.getString(4));
params.setScope(resultSet.getString(5));
params.setOauthTokenVerifier(resultSet.getString(7));
params.setAuthorizedbyUserName(resultSet.getString(8));
} else {
throw new IdentityException("Invalid request token : " + oauthToken);
}
connection.commit();
} catch (SQLException e) {
throw new IdentityException("Error when retrieving request token from the persistence store : " +
oauthToken);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return params;
}
public void issueAccessToken(String consumerKey, String accessToken, String accessTokenSecret,
String requestToken, String authorizedUser, String scope) throws IdentityOAuthAdminException {
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement removeReqTokStmt = null;
PreparedStatement issueAccessTokStmt = null;
try {
removeReqTokStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.REMOVE_REQUEST_TOKEN);
removeReqTokStmt.setString(1, requestToken);
removeReqTokStmt.execute();
issueAccessTokStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.ADD_ACCESS_TOKEN);
issueAccessTokStmt.setString(1, accessToken);
issueAccessTokStmt.setString(2, accessTokenSecret);
issueAccessTokStmt.setString(3, consumerKey);
issueAccessTokStmt.setString(4, scope);
issueAccessTokStmt.setString(5, authorizedUser);
issueAccessTokStmt.execute();
connection.commit();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new IdentityOAuthAdminException("Error when creating the request token for consumer : " + consumerKey);
} finally {
IdentityDatabaseUtil.closeStatement(issueAccessTokStmt);
IdentityDatabaseUtil.closeAllConnections(connection, null, removeReqTokStmt);
}
}
/**
* Validating the access token. Should be equal in the scope where the original request token
* been issued to.If this matches, the method returns the user who authorized the request token.
*
* @param consumerKey Consumer Key
* @param oauthToken Access Token
* @param reqScope Scope in the request
* @return Authorized Username
* @throws IdentityException Error when reading token information from persistence store or invalid token or invalid scope.
*/
public String validateAccessToken(String consumerKey, String oauthToken, String reqScope)
throws IdentityException {
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
String scope = null;
String authorizedUser = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_ACCESS_TOKEN);
prepStmt.setString(1, oauthToken);
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
scope = resultSet.getString(1);
authorizedUser = resultSet.getString(2);
} else {
throw new IdentityException("Invalid access token : " + oauthToken);
}
connection.commit();
} catch (SQLException e) {
throw new IdentityOAuthAdminException("Error when reading the callback url for consumer key : " +
consumerKey, e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
if (reqScope != null && reqScope.equals(scope)) {
return authorizedUser;
} else {
throw new IdentityException("Scope of the access token doesn't match with the original scope");
}
}
private String getCallbackURLOfApp(String consumerKey) throws IdentityOAuthAdminException {
String callbackURL = null;
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_REGISTERED_CALLBACK_URL);
prepStmt.setString(1, consumerKey);
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
callbackURL = resultSet.getString(1);
}
connection.commit();
} catch (SQLException e) {
throw new IdentityOAuthAdminException("Error when reading the callback url for consumer key : " +
consumerKey, e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return callbackURL;
}
private String getCallbackURLOfReqToken(String oauthToken) throws IdentityOAuthAdminException {
String callbackURL = null;
Connection connection = IdentityDatabaseUtil.getDBConnection();
PreparedStatement prepStmt = null;
ResultSet resultSet = null;
try {
prepStmt = connection.prepareStatement(SQLQueries.OAuthConsumerDAOSQLQueries.GET_CALLBACK_URL_OF_REQ_TOKEN);
prepStmt.setString(1, oauthToken);
resultSet = prepStmt.executeQuery();
if (resultSet.next()) {
callbackURL = resultSet.getString(1);
}
connection.commit();
} catch (SQLException e) {
throw new IdentityOAuthAdminException("Error when reading the callback url for OAuth Token : " +
oauthToken, e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt);
}
return callbackURL;
}
}
| pulasthi7/carbon-identity | components/oauth/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/dao/OAuthConsumerDAO.java | Java | apache-2.0 | 17,251 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.p2p;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import org.apache.ignite.Ignite;
import org.apache.ignite.compute.ComputeTask;
import org.apache.ignite.configuration.DeploymentMode;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.deployment.local.LocalDeploymentSpi;
import org.apache.ignite.testframework.GridTestClassLoader;
import org.apache.ignite.testframework.config.GridTestProperties;
import org.apache.ignite.testframework.junits.IgniteTestResources;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.testframework.junits.common.GridCommonTest;
/**
*
*/
@SuppressWarnings({"ProhibitedExceptionDeclared"})
@GridCommonTest(group = "P2P")
public class GridP2PUndeploySelfTest extends GridCommonAbstractTest {
/** Current deployment mode. Used in {@link #getConfiguration(String)}. */
private DeploymentMode depMode;
/** Class Name of task. */
private static final String TEST_TASK_NAME = "org.apache.ignite.tests.p2p.P2PTestTaskExternalPath1";
/** */
private Map<String, LocalDeploymentSpi> spis = new HashMap<>();
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName,
IgniteTestResources rsrcs) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName, rsrcs);
LocalDeploymentSpi spi = new LocalDeploymentSpi();
spis.put(igniteInstanceName, spi);
cfg.setDeploymentSpi(spi);
cfg.setDeploymentMode(depMode);
return cfg;
}
/**
* @param depMode deployment mode.
* @throws Exception If failed.
*/
@SuppressWarnings("unchecked")
private void processTestUndeployLocalTasks(DeploymentMode depMode) throws Exception {
try {
this.depMode = depMode;
Ignite ignite1 = startGrid(1);
Ignite ignite2 = startGrid(2);
ClassLoader tstClsLdr = new GridTestClassLoader(GridP2PTestTask.class.getName(),
GridP2PTestJob.class.getName());
Class<? extends ComputeTask<?, ?>> task1 =
(Class<? extends ComputeTask<?, ?>>)tstClsLdr.loadClass(GridP2PTestTask.class.getName());
ignite1.compute().localDeployTask(task1, tstClsLdr);
ignite1.compute().execute(task1.getName(), 1);
ignite2.compute().localDeployTask(task1, tstClsLdr);
ignite2.compute().execute(task1.getName(), 2);
LocalDeploymentSpi spi1 = spis.get(ignite1.name());
LocalDeploymentSpi spi2 = spis.get(ignite2.name());
assert spi1.findResource(task1.getName()) != null;
assert spi2.findResource(task1.getName()) != null;
assert ignite1.compute().localTasks().containsKey(task1.getName());
assert ignite2.compute().localTasks().containsKey(task1.getName());
ignite2.compute().undeployTask(task1.getName());
// Wait for undeploy.
Thread.sleep(1000);
assert spi1.findResource(task1.getName()) == null;
assert spi2.findResource(task1.getName()) == null;
assert !ignite1.compute().localTasks().containsKey(task1.getName());
assert !ignite2.compute().localTasks().containsKey(task1.getName());
}
finally {
stopGrid(2);
stopGrid(1);
}
}
/**
* @param depMode deployment mode.
* @throws Exception If failed.
*/
@SuppressWarnings("unchecked")
private void processTestUndeployP2PTasks(DeploymentMode depMode) throws Exception {
try {
this.depMode = depMode;
Ignite ignite1 = startGrid(1);
Ignite ignite2 = startGrid(2);
ClassLoader ldr = new URLClassLoader(new URL[] {new URL(GridTestProperties.getProperty("p2p.uri.cls"))},
GridP2PSameClassLoaderSelfTest.class.getClassLoader());
Class<? extends ComputeTask<?, ?>> task1 =
(Class<? extends ComputeTask<?, ?>>)ldr.loadClass(TEST_TASK_NAME);
ignite1.compute().localDeployTask(task1, ldr);
ignite1.compute().execute(task1.getName(), ignite2.cluster().localNode().id());
LocalDeploymentSpi spi1 = spis.get(ignite1.name());
LocalDeploymentSpi spi2 = spis.get(ignite2.name());
assert spi1.findResource(task1.getName()) != null;
assert ignite1.compute().localTasks().containsKey(task1.getName());
// P2P deployment will not deploy task into the SPI.
assert spi2.findResource(task1.getName()) == null;
ignite1.compute().undeployTask(task1.getName());
// Wait for undeploy.
Thread.sleep(1000);
assert spi1.findResource(task1.getName()) == null;
assert spi2.findResource(task1.getName()) == null;
assert !ignite1.compute().localTasks().containsKey(task1.getName());
assert !ignite2.compute().localTasks().containsKey(task1.getName());
spis = null;
}
finally {
stopGrid(2);
stopGrid(1);
}
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#PRIVATE} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployLocalPrivateMode() throws Exception {
processTestUndeployLocalTasks(DeploymentMode.PRIVATE);
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#ISOLATED} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployLocalIsolatedMode() throws Exception {
processTestUndeployLocalTasks(DeploymentMode.ISOLATED);
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#CONTINUOUS} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployLocalContinuousMode() throws Exception {
processTestUndeployLocalTasks(DeploymentMode.CONTINUOUS);
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#SHARED} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployLocalSharedMode() throws Exception {
processTestUndeployLocalTasks(DeploymentMode.SHARED);
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#PRIVATE} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployP2PPrivateMode() throws Exception {
processTestUndeployP2PTasks(DeploymentMode.PRIVATE);
}
/**
* Test GridDeploymentMode.ISOLATED mode.
*
* @throws Exception if error occur.
*/
public void testUndeployP2PIsolatedMode() throws Exception {
processTestUndeployP2PTasks(DeploymentMode.ISOLATED);
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#CONTINUOUS} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployP2PContinuousMode() throws Exception {
processTestUndeployP2PTasks(DeploymentMode.CONTINUOUS);
}
/**
* Test {@link org.apache.ignite.configuration.DeploymentMode#SHARED} mode.
*
* @throws Exception if error occur.
*/
public void testUndeployP2PSharedMode() throws Exception {
processTestUndeployP2PTasks(DeploymentMode.SHARED);
}
} | alexzaitzev/ignite | modules/core/src/test/java/org/apache/ignite/p2p/GridP2PUndeploySelfTest.java | Java | apache-2.0 | 8,325 |
/*
* Copyright 2013 Cloudera Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kitesdk.data;
/**
* <p>
* Exception thrown to indicate that there was a problem
* parsing or validating a schema, partition strategy, or column mapping.
* <p>
*
* @since 0.14.0
*/
public class ValidationException extends DatasetException {
public ValidationException(String msg) {
super(msg);
}
public ValidationException(Throwable cause) {
super(cause);
}
public ValidationException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Precondition-style validation that throws a {@link ValidationException}.
*
* @param isValid
* {@code true} if valid, {@code false} if an exception should be
* thrown
* @param message
* A String message for the exception.
*/
public static void check(boolean isValid, String message, Object... args) {
if (!isValid) {
String[] argStrings = new String[args.length];
for (int i = 0; i < args.length; i += 1) {
argStrings[i] = String.valueOf(args[i]);
}
throw new ValidationException(
String.format(String.valueOf(message), (Object[]) argStrings));
}
}
}
| dlanza1/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/ValidationException.java | Java | apache-2.0 | 1,742 |
/* 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.camunda.bpm.qa.performance.engine.bpmn;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE1;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE10;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE2;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE3;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE4;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE5;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE6;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE7;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE8;
import static org.camunda.bpm.qa.performance.engine.steps.PerfTestConstants.VARIABLE9;
import java.util.HashMap;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.qa.performance.engine.junit.ProcessEnginePerformanceTestCase;
import org.camunda.bpm.qa.performance.engine.steps.StartProcessInstanceStep;
import org.junit.Test;
/**
* @author Daniel Meyer
*
*/
public class VariablesPerformanceTest extends ProcessEnginePerformanceTestCase {
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEventStringVar() {
HashMap<String, Object> variables = new HashMap<String, Object>();
variables.put(VARIABLE1, "someValue");
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEvent10StringVars() {
HashMap<String, Object> variables = new HashMap<String, Object>();
variables.put(VARIABLE1, "someValue");
variables.put(VARIABLE2, "someValue");
variables.put(VARIABLE3, "someValue");
variables.put(VARIABLE4, "someValue");
variables.put(VARIABLE5, "someValue");
variables.put(VARIABLE6, "someValue");
variables.put(VARIABLE7, "someValue");
variables.put(VARIABLE8, "someValue");
variables.put(VARIABLE9, "someValue");
variables.put(VARIABLE10, "someValue");
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEventStringVar2() {
HashMap<String, Object> variables = new HashMap<String, Object>();
variables.put(VARIABLE1, "Some Text which is considerably longer than the first one.");
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEventDoubleVar() {
HashMap<String, Object> variables = new HashMap<String, Object>();
variables.put(VARIABLE1, 2d);
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEventByteVar() {
HashMap<String, Object> variables = new HashMap<String, Object>();
variables.put(VARIABLE1, "This string will be saved as a byte array.".getBytes());
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEvent10ByteVars() {
HashMap<String, Object> variables = new HashMap<String, Object>();
variables.put(VARIABLE1, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE2, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE3, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE4, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE5, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE6, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE7, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE8, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE9, "This string will be saved as a byte array.".getBytes());
variables.put(VARIABLE10, "This string will be saved as a byte array.".getBytes());
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
@Test
@Deployment(resources =
{"org/camunda/bpm/qa/performance/engine/bpmn/StartEventPerformanceTest.noneStartEvent.bpmn"})
public void noneStartEventLargeByteVar() {
HashMap<String, Object> variables = new HashMap<String, Object>();
byte[] bytes = new byte[5*1024];
variables.put(VARIABLE1, bytes);
performanceTest()
.step(new StartProcessInstanceStep(engine, "process", variables))
.run();
}
}
| nagyistoce/camunda-bpm-platform | qa/performance-tests-engine/src/test/java/org/camunda/bpm/qa/performance/engine/bpmn/VariablesPerformanceTest.java | Java | apache-2.0 | 6,001 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.geo.builders;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.unit.DistanceUnit.Distance;
import org.elasticsearch.common.xcontent.XContentBuilder;
import com.spatial4j.core.shape.Circle;
import com.vividsolutions.jts.geom.Coordinate;
import java.io.IOException;
public class CircleBuilder extends ShapeBuilder {
public static final String FIELD_RADIUS = "radius";
public static final GeoShapeType TYPE = GeoShapeType.CIRCLE;
private DistanceUnit unit;
private double radius;
private Coordinate center;
/**
* Set the center of the circle
*
* @param center coordinate of the circles center
* @return this
*/
public CircleBuilder center(Coordinate center) {
this.center = center;
return this;
}
/**
* set the center of the circle
* @param lon longitude of the center
* @param lat latitude of the center
* @return this
*/
public CircleBuilder center(double lon, double lat) {
return center(new Coordinate(lon, lat));
}
/**
* Set the radius of the circle. The String value will be parsed by {@link DistanceUnit}
* @param radius Value and unit of the circle combined in a string
* @return this
*/
public CircleBuilder radius(String radius) {
return radius(DistanceUnit.Distance.parseDistance(radius));
}
/**
* Set the radius of the circle
* @param radius radius of the circle (see {@link DistanceUnit.Distance})
* @return this
*/
public CircleBuilder radius(Distance radius) {
return radius(radius.value, radius.unit);
}
/**
* Set the radius of the circle
* @param radius value of the circles radius
* @param unit unit name of the radius value (see {@link DistanceUnit})
* @return this
*/
public CircleBuilder radius(double radius, String unit) {
return radius(radius, DistanceUnit.fromString(unit));
}
/**
* Set the radius of the circle
* @param radius value of the circles radius
* @param unit unit of the radius value (see {@link DistanceUnit})
* @return this
*/
public CircleBuilder radius(double radius, DistanceUnit unit) {
this.unit = unit;
this.radius = radius;
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(FIELD_TYPE, TYPE.shapename);
builder.field(FIELD_RADIUS, unit.toString(radius));
builder.field(FIELD_COORDINATES);
toXContent(builder, center);
return builder.endObject();
}
@Override
public Circle build() {
return SPATIAL_CONTEXT.makeCircle(center.x, center.y, 180 * radius / unit.getEarthCircumference());
}
@Override
public GeoShapeType type() {
return TYPE;
}
}
| corochoone/elasticsearch | src/main/java/org/elasticsearch/common/geo/builders/CircleBuilder.java | Java | apache-2.0 | 3,769 |
/*
* 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.spark.network.shuffle;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import org.apache.spark.network.util.MapConfigProvider;
import org.apache.spark.network.util.TransportConf;
public class NonShuffleFilesCleanupSuite {
// Same-thread Executor used to ensure cleanup happens synchronously in test thread.
private Executor sameThreadExecutor = MoreExecutors.sameThreadExecutor();
private TransportConf conf = new TransportConf("shuffle", MapConfigProvider.EMPTY);
private static final String SORT_MANAGER = "org.apache.spark.shuffle.sort.SortShuffleManager";
@Test
public void cleanupOnRemovedExecutorWithShuffleFiles() throws IOException {
cleanupOnRemovedExecutor(true);
}
@Test
public void cleanupOnRemovedExecutorWithoutShuffleFiles() throws IOException {
cleanupOnRemovedExecutor(false);
}
private void cleanupOnRemovedExecutor(boolean withShuffleFiles) throws IOException {
TestShuffleDataContext dataContext = initDataContext(withShuffleFiles);
ExternalShuffleBlockResolver resolver =
new ExternalShuffleBlockResolver(conf, null, sameThreadExecutor);
resolver.registerExecutor("app", "exec0", dataContext.createExecutorInfo(SORT_MANAGER));
resolver.executorRemoved("exec0", "app");
assertCleanedUp(dataContext);
}
@Test
public void cleanupUsesExecutorWithShuffleFiles() throws IOException {
cleanupUsesExecutor(true);
}
@Test
public void cleanupUsesExecutorWithoutShuffleFiles() throws IOException {
cleanupUsesExecutor(false);
}
private void cleanupUsesExecutor(boolean withShuffleFiles) throws IOException {
TestShuffleDataContext dataContext = initDataContext(withShuffleFiles);
AtomicBoolean cleanupCalled = new AtomicBoolean(false);
// Executor which does nothing to ensure we're actually using it.
Executor noThreadExecutor = runnable -> cleanupCalled.set(true);
ExternalShuffleBlockResolver manager =
new ExternalShuffleBlockResolver(conf, null, noThreadExecutor);
manager.registerExecutor("app", "exec0", dataContext.createExecutorInfo(SORT_MANAGER));
manager.executorRemoved("exec0", "app");
assertTrue(cleanupCalled.get());
assertStillThere(dataContext);
}
@Test
public void cleanupOnlyRemovedExecutorWithShuffleFiles() throws IOException {
cleanupOnlyRemovedExecutor(true);
}
@Test
public void cleanupOnlyRemovedExecutorWithoutShuffleFiles() throws IOException {
cleanupOnlyRemovedExecutor(false);
}
private void cleanupOnlyRemovedExecutor(boolean withShuffleFiles) throws IOException {
TestShuffleDataContext dataContext0 = initDataContext(withShuffleFiles);
TestShuffleDataContext dataContext1 = initDataContext(withShuffleFiles);
ExternalShuffleBlockResolver resolver =
new ExternalShuffleBlockResolver(conf, null, sameThreadExecutor);
resolver.registerExecutor("app", "exec0", dataContext0.createExecutorInfo(SORT_MANAGER));
resolver.registerExecutor("app", "exec1", dataContext1.createExecutorInfo(SORT_MANAGER));
resolver.executorRemoved("exec-nonexistent", "app");
assertStillThere(dataContext0);
assertStillThere(dataContext1);
resolver.executorRemoved("exec0", "app");
assertCleanedUp(dataContext0);
assertStillThere(dataContext1);
resolver.executorRemoved("exec1", "app");
assertCleanedUp(dataContext0);
assertCleanedUp(dataContext1);
// Make sure it's not an error to cleanup multiple times
resolver.executorRemoved("exec1", "app");
assertCleanedUp(dataContext0);
assertCleanedUp(dataContext1);
}
@Test
public void cleanupOnlyRegisteredExecutorWithShuffleFiles() throws IOException {
cleanupOnlyRegisteredExecutor(true);
}
@Test
public void cleanupOnlyRegisteredExecutorWithoutShuffleFiles() throws IOException {
cleanupOnlyRegisteredExecutor(false);
}
private void cleanupOnlyRegisteredExecutor(boolean withShuffleFiles) throws IOException {
TestShuffleDataContext dataContext = initDataContext(withShuffleFiles);
ExternalShuffleBlockResolver resolver =
new ExternalShuffleBlockResolver(conf, null, sameThreadExecutor);
resolver.registerExecutor("app", "exec0", dataContext.createExecutorInfo(SORT_MANAGER));
resolver.executorRemoved("exec1", "app");
assertStillThere(dataContext);
resolver.executorRemoved("exec0", "app");
assertCleanedUp(dataContext);
}
private static void assertStillThere(TestShuffleDataContext dataContext) {
for (String localDir : dataContext.localDirs) {
assertTrue(localDir + " was cleaned up prematurely", new File(localDir).exists());
}
}
private static FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// Don't delete shuffle data or shuffle index files.
return !name.endsWith(".index") && !name.endsWith(".data");
}
};
private static boolean assertOnlyShuffleDataInDir(File[] dirs) {
for (File dir : dirs) {
assertTrue(dir.getName() + " wasn't cleaned up", !dir.exists() ||
dir.listFiles(filter).length == 0 || assertOnlyShuffleDataInDir(dir.listFiles()));
}
return true;
}
private static void assertCleanedUp(TestShuffleDataContext dataContext) {
for (String localDir : dataContext.localDirs) {
File[] dirs = new File[] {new File(localDir)};
assertOnlyShuffleDataInDir(dirs);
}
}
private static TestShuffleDataContext initDataContext(boolean withShuffleFiles)
throws IOException {
if (withShuffleFiles) {
return initDataContextWithShuffleFiles();
} else {
return initDataContextWithoutShuffleFiles();
}
}
private static TestShuffleDataContext initDataContextWithShuffleFiles() throws IOException {
TestShuffleDataContext dataContext = createDataContext();
createShuffleFiles(dataContext);
createNonShuffleFiles(dataContext);
return dataContext;
}
private static TestShuffleDataContext initDataContextWithoutShuffleFiles() throws IOException {
TestShuffleDataContext dataContext = createDataContext();
createNonShuffleFiles(dataContext);
return dataContext;
}
private static TestShuffleDataContext createDataContext() {
TestShuffleDataContext dataContext = new TestShuffleDataContext(10, 5);
dataContext.create();
return dataContext;
}
private static void createShuffleFiles(TestShuffleDataContext dataContext) throws IOException {
Random rand = new Random(123);
dataContext.insertSortShuffleData(rand.nextInt(1000), rand.nextInt(1000), new byte[][] {
"ABC".getBytes(StandardCharsets.UTF_8),
"DEF".getBytes(StandardCharsets.UTF_8)});
}
private static void createNonShuffleFiles(TestShuffleDataContext dataContext) throws IOException {
// Create spill file(s)
dataContext.insertSpillData();
}
}
| bravo-zhang/spark | common/network-shuffle/src/test/java/org/apache/spark/network/shuffle/NonShuffleFilesCleanupSuite.java | Java | apache-2.0 | 7,992 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cli;
import org.elasticsearch.common.SuppressForbidden;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
/**
* A Terminal wraps access to reading input and writing output for a cli.
*
* The available methods are similar to those of {@link Console}, with the ability
* to read either normal text or a password, and the ability to print a line
* of text. Printing is also gated by the {@link Verbosity} of the terminal,
* which allows {@link #println(Verbosity,String)} calls which act like a logger,
* only actually printing if the verbosity level of the terminal is above
* the verbosity of the message.
*/
public abstract class Terminal {
/** The default terminal implementation, which will be a console if available, or stdout/stderr if not. */
public static final Terminal DEFAULT = ConsoleTerminal.isSupported() ? new ConsoleTerminal() : new SystemTerminal();
/** Defines the available verbosity levels of messages to be printed. */
public enum Verbosity {
SILENT, /* always printed */
NORMAL, /* printed when no options are given to cli */
VERBOSE /* printed only when cli is passed verbose option */
}
/** The current verbosity for the terminal, defaulting to {@link Verbosity#NORMAL}. */
private Verbosity verbosity = Verbosity.NORMAL;
/** The newline used when calling println. */
private final String lineSeparator;
protected Terminal(String lineSeparator) {
this.lineSeparator = lineSeparator;
}
/** Sets the verbosity of the terminal. */
public void setVerbosity(Verbosity verbosity) {
this.verbosity = verbosity;
}
/** Reads clear text from the terminal input. See {@link Console#readLine()}. */
public abstract String readText(String prompt);
/** Reads password text from the terminal input. See {@link Console#readPassword()}}. */
public abstract char[] readSecret(String prompt);
/** Returns a Writer which can be used to write to the terminal directly. */
public abstract PrintWriter getWriter();
/** Prints a line to the terminal at {@link Verbosity#NORMAL} verbosity level. */
public final void println(String msg) {
println(Verbosity.NORMAL, msg);
}
/** Prints a line to the terminal at {@code verbosity} level. */
public final void println(Verbosity verbosity, String msg) {
print(verbosity, msg + lineSeparator);
}
/** Prints message to the terminal at {@code verbosity} level, without a newline. */
public final void print(Verbosity verbosity, String msg) {
if (this.verbosity.ordinal() >= verbosity.ordinal()) {
getWriter().print(msg);
getWriter().flush();
}
}
private static class ConsoleTerminal extends Terminal {
private static final Console CONSOLE = System.console();
ConsoleTerminal() {
super(System.lineSeparator());
}
static boolean isSupported() {
return CONSOLE != null;
}
@Override
public PrintWriter getWriter() {
return CONSOLE.writer();
}
@Override
public String readText(String prompt) {
return CONSOLE.readLine("%s", prompt);
}
@Override
public char[] readSecret(String prompt) {
return CONSOLE.readPassword("%s", prompt);
}
}
private static class SystemTerminal extends Terminal {
private static final PrintWriter WRITER = newWriter();
SystemTerminal() {
super(System.lineSeparator());
}
@SuppressForbidden(reason = "Writer for System.out")
private static PrintWriter newWriter() {
return new PrintWriter(System.out);
}
@Override
public PrintWriter getWriter() {
return WRITER;
}
@Override
public String readText(String text) {
getWriter().print(text);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
try {
return reader.readLine();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public char[] readSecret(String text) {
return readText(text).toCharArray();
}
}
}
| strahanjen/strahanjen.github.io | elasticsearch-master/core/src/main/java/org/elasticsearch/cli/Terminal.java | Java | bsd-3-clause | 5,330 |
/***
Copyright (c) 2008-2012 CommonsWare, 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.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.sqlcipher;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
public class ConstantsBrowser extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int ADD_ID=Menu.FIRST + 1;
private static final int DELETE_ID=Menu.FIRST + 3;
private static final String[] PROJECTION=new String[] {
Provider.Constants._ID, Provider.Constants.TITLE,
Provider.Constants.VALUE };
private SimpleCursorAdapter adapter=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getContentResolver().call(Provider.Constants.CONTENT_URI,
Provider.SET_KEY_METHOD, "sekrit", null);
adapter=
new SimpleCursorAdapter(this, R.layout.row, null, new String[] {
Provider.Constants.TITLE, Provider.Constants.VALUE },
new int[] { R.id.title, R.id.value });
setListAdapter(adapter);
registerForContextMenu(getListView());
getLoaderManager().initLoader(0, null, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, ADD_ID, Menu.NONE, "Add")
.setIcon(R.drawable.add).setAlphabeticShortcut('a');
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ADD_ID:
add();
return(true);
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
.setIcon(R.drawable.delete).setAlphabeticShortcut('d');
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterView.AdapterContextMenuInfo info=
(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
delete(info.id);
return(true);
}
return(super.onOptionsItemSelected(item));
}
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
return(new CursorLoader(this, Provider.Constants.CONTENT_URI,
PROJECTION, null, null, null));
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
private void add() {
LayoutInflater inflater=LayoutInflater.from(this);
View addView=inflater.inflate(R.layout.add_edit, null);
final DialogWrapper wrapper=new DialogWrapper(addView);
new AlertDialog.Builder(this).setTitle(R.string.add_title)
.setView(addView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
processAdd(wrapper);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ignore,
// just
// dismiss
}
}).show();
}
private void delete(final long rowId) {
if (rowId > 0) {
new AlertDialog.Builder(this).setTitle(R.string.delete_title)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
processDelete(rowId);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// ignore,
// just
// dismiss
}
}).show();
}
}
private void processAdd(DialogWrapper wrapper) {
ContentValues values=new ContentValues(2);
values.put(Provider.Constants.TITLE, wrapper.getTitle());
values.put(Provider.Constants.VALUE, wrapper.getValue());
getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
}
private void processDelete(long rowId) {
String[] args= { String.valueOf(rowId) };
getContentResolver().delete(Provider.Constants.CONTENT_URI,
Provider.Constants._ID + "=?", args);
}
class DialogWrapper {
EditText titleField=null;
EditText valueField=null;
View base=null;
DialogWrapper(View base) {
this.base=base;
valueField=(EditText)base.findViewById(R.id.value);
}
String getTitle() {
return(getTitleField().getText().toString());
}
float getValue() {
return(new Float(getValueField().getText().toString()).floatValue());
}
private EditText getTitleField() {
if (titleField == null) {
titleField=(EditText)base.findViewById(R.id.title);
}
return(titleField);
}
private EditText getValueField() {
if (valueField == null) {
valueField=(EditText)base.findViewById(R.id.value);
}
return(valueField);
}
}
} | Jumshaid/empublite | Gradle/ConstantsSecure/src/main/java/com/commonsware/android/sqlcipher/ConstantsBrowser.java | Java | apache-2.0 | 7,926 |
/**
* Copyright (c) 2010-2016, openHAB.org 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
*/
package org.openhab.binding.satel.internal.types;
/**
* Available zone states.
*
* @author Krzysztof Goworek
* @since 1.7.0
*/
public enum ZoneState implements StateType {
VIOLATION(0x00),
TAMPER(0x01),
ALARM(0x02),
TAMPER_ALARM(0x03),
ALARM_MEMORY(0x04),
TAMPER_ALARM_MEMORY(0x05),
BYPASS(0x06),
NO_VIOLATION_TROUBLE(0x07),
LONG_VIOLATION_TROUBLE(0x08),
ISOLATE(0x26),
MASKED(0x28),
MASKED_MEMORY(0x29);
private byte refreshCommand;
ZoneState(int refreshCommand) {
this.refreshCommand = (byte) refreshCommand;
}
/**
* {@inheritDoc}
*/
@Override
public byte getRefreshCommand() {
return refreshCommand;
}
/**
* {@inheritDoc}
*/
@Override
public ObjectType getObjectType() {
return ObjectType.ZONE;
}
}
| paolodenti/openhab | bundles/binding/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/types/ZoneState.java | Java | epl-1.0 | 1,209 |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package compiler.jvmci.common.testcases;
// just a most common simple class with method "testMethod" to use anywhere
public class SimpleClass {
public void testMethod() {
// empty
}
}
| md-5/jdk10 | test/hotspot/jtreg/compiler/jvmci/common/testcases/SimpleClass.java | Java | gpl-2.0 | 1,254 |
/*
* Copyright (C) 2010 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.example.android.tictactoe.library;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.example.android.tictactoe.library.GameView.ICellListener;
import com.example.android.tictactoe.library.GameView.State;
public class GameActivity extends Activity {
/** Start player. Must be 1 or 2. Default is 1. */
public static final String EXTRA_START_PLAYER =
"com.example.android.tictactoe.library.GameActivity.EXTRA_START_PLAYER";
private static final int MSG_COMPUTER_TURN = 1;
private static final long COMPUTER_DELAY_MS = 500;
private Handler mHandler = new Handler(new MyHandlerCallback());
private Random mRnd = new Random();
private GameView mGameView;
private TextView mInfoView;
private Button mButtonNext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
/*
* IMPORTANT: all resource IDs from this library will eventually be merged
* with the resources from the main project that will use the library.
*
* If the main project and the libraries define the same resource IDs,
* the application project will always have priority and override library resources
* and IDs defined in multiple libraries are resolved based on the libraries priority
* defined in the main project.
*
* An intentional consequence is that the main project can override some resources
* from the library.
* (TODO insert example).
*
* To avoid potential conflicts, it is suggested to add a prefix to the
* library resource names.
*/
setContentView(R.layout.lib_game);
mGameView = (GameView) findViewById(R.id.game_view);
mInfoView = (TextView) findViewById(R.id.info_turn);
mButtonNext = (Button) findViewById(R.id.next_turn);
mGameView.setFocusable(true);
mGameView.setFocusableInTouchMode(true);
mGameView.setCellListener(new MyCellListener());
mButtonNext.setOnClickListener(new MyButtonListener());
}
@Override
protected void onResume() {
super.onResume();
State player = mGameView.getCurrentPlayer();
if (player == State.UNKNOWN) {
player = State.fromInt(getIntent().getIntExtra(EXTRA_START_PLAYER, 1));
if (!checkGameFinished(player)) {
selectTurn(player);
}
}
if (player == State.PLAYER2) {
mHandler.sendEmptyMessageDelayed(MSG_COMPUTER_TURN, COMPUTER_DELAY_MS);
}
if (player == State.WIN) {
setWinState(mGameView.getWinner());
}
}
private State selectTurn(State player) {
mGameView.setCurrentPlayer(player);
mButtonNext.setEnabled(false);
if (player == State.PLAYER1) {
mInfoView.setText(R.string.player1_turn);
mGameView.setEnabled(true);
} else if (player == State.PLAYER2) {
mInfoView.setText(R.string.player2_turn);
mGameView.setEnabled(false);
}
return player;
}
private class MyCellListener implements ICellListener {
public void onCellSelected() {
if (mGameView.getCurrentPlayer() == State.PLAYER1) {
int cell = mGameView.getSelection();
mButtonNext.setEnabled(cell >= 0);
}
}
}
private class MyButtonListener implements OnClickListener {
public void onClick(View v) {
State player = mGameView.getCurrentPlayer();
if (player == State.WIN) {
GameActivity.this.finish();
} else if (player == State.PLAYER1) {
int cell = mGameView.getSelection();
if (cell >= 0) {
mGameView.stopBlink();
mGameView.setCell(cell, player);
finishTurn();
}
}
}
}
private class MyHandlerCallback implements Callback {
public boolean handleMessage(Message msg) {
if (msg.what == MSG_COMPUTER_TURN) {
// Pick a non-used cell at random. That's about all the AI you need for this game.
State[] data = mGameView.getData();
int used = 0;
while (used != 0x1F) {
int index = mRnd.nextInt(9);
if (((used >> index) & 1) == 0) {
used |= 1 << index;
if (data[index] == State.EMPTY) {
mGameView.setCell(index, mGameView.getCurrentPlayer());
break;
}
}
}
finishTurn();
return true;
}
return false;
}
}
private State getOtherPlayer(State player) {
return player == State.PLAYER1 ? State.PLAYER2 : State.PLAYER1;
}
private void finishTurn() {
State player = mGameView.getCurrentPlayer();
if (!checkGameFinished(player)) {
player = selectTurn(getOtherPlayer(player));
if (player == State.PLAYER2) {
mHandler.sendEmptyMessageDelayed(MSG_COMPUTER_TURN, COMPUTER_DELAY_MS);
}
}
}
public boolean checkGameFinished(State player) {
State[] data = mGameView.getData();
boolean full = true;
int col = -1;
int row = -1;
int diag = -1;
// check rows
for (int j = 0, k = 0; j < 3; j++, k += 3) {
if (data[k] != State.EMPTY && data[k] == data[k+1] && data[k] == data[k+2]) {
row = j;
}
if (full && (data[k] == State.EMPTY ||
data[k+1] == State.EMPTY ||
data[k+2] == State.EMPTY)) {
full = false;
}
}
// check columns
for (int i = 0; i < 3; i++) {
if (data[i] != State.EMPTY && data[i] == data[i+3] && data[i] == data[i+6]) {
col = i;
}
}
// check diagonals
if (data[0] != State.EMPTY && data[0] == data[1+3] && data[0] == data[2+6]) {
diag = 0;
} else if (data[2] != State.EMPTY && data[2] == data[1+3] && data[2] == data[0+6]) {
diag = 1;
}
if (col != -1 || row != -1 || diag != -1) {
setFinished(player, col, row, diag);
return true;
}
// if we get here, there's no winner but the board is full.
if (full) {
setFinished(State.EMPTY, -1, -1, -1);
return true;
}
return false;
}
private void setFinished(State player, int col, int row, int diagonal) {
mGameView.setCurrentPlayer(State.WIN);
mGameView.setWinner(player);
mGameView.setEnabled(false);
mGameView.setFinished(col, row, diagonal);
setWinState(player);
}
private void setWinState(State player) {
mButtonNext.setEnabled(true);
mButtonNext.setText("Back");
String text;
if (player == State.EMPTY) {
text = getString(R.string.tie);
} else if (player == State.PLAYER1) {
text = getString(R.string.player1_win);
} else {
text = getString(R.string.player2_win);
}
mInfoView.setText(text);
}
}
| dickroberts/mvn-android | tictactoe/tictactoe-lib/src/main/java/com/example/android/tictactoe/library/GameActivity.java | Java | apache-2.0 | 8,430 |
package org.apache.lucene.analysis.de;
/*
* 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 java.util.Map;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.de.GermanNormalizationFilter;
import org.apache.lucene.analysis.util.AbstractAnalysisFactory;
import org.apache.lucene.analysis.util.MultiTermAwareComponent;
import org.apache.lucene.analysis.util.TokenFilterFactory;
/**
* Factory for {@link GermanNormalizationFilter}.
* <pre class="prettyprint">
* <fieldType name="text_denorm" class="solr.TextField" positionIncrementGap="100">
* <analyzer>
* <tokenizer class="solr.StandardTokenizerFactory"/>
* <filter class="solr.LowerCaseFilterFactory"/>
* <filter class="solr.GermanNormalizationFilterFactory"/>
* </analyzer>
* </fieldType></pre>
*/
public class GermanNormalizationFilterFactory extends TokenFilterFactory implements MultiTermAwareComponent {
/** Creates a new GermanNormalizationFilterFactory */
public GermanNormalizationFilterFactory(Map<String,String> args) {
super(args);
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
@Override
public TokenStream create(TokenStream input) {
return new GermanNormalizationFilter(input);
}
@Override
public AbstractAnalysisFactory getMultiTermComponent() {
return this;
}
}
| smartan/lucene | src/main/java/org/apache/lucene/analysis/de/GermanNormalizationFilterFactory.java | Java | apache-2.0 | 2,185 |
package mono.android.support.v4.app;
public class FragmentManager_OnBackStackChangedListenerImplementor
extends java.lang.Object
implements
mono.android.IGCUserPeer,
android.support.v4.app.FragmentManager.OnBackStackChangedListener
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_onBackStackChanged:()V:GetOnBackStackChangedHandler:Android.Support.V4.App.FragmentManager/IOnBackStackChangedListenerInvoker, Xamarin.Android.Support.v4\n" +
"";
mono.android.Runtime.register ("Android.Support.V4.App.FragmentManager+IOnBackStackChangedListenerImplementor, Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", FragmentManager_OnBackStackChangedListenerImplementor.class, __md_methods);
}
public FragmentManager_OnBackStackChangedListenerImplementor () throws java.lang.Throwable
{
super ();
if (getClass () == FragmentManager_OnBackStackChangedListenerImplementor.class)
mono.android.TypeManager.Activate ("Android.Support.V4.App.FragmentManager+IOnBackStackChangedListenerImplementor, Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] { });
}
public void onBackStackChanged ()
{
n_onBackStackChanged ();
}
private native void n_onBackStackChanged ();
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| Ecoczdrumercz/XamApp | testTest/testTest/testTest.Android/obj/Debug/android/src/mono/android/support/v4/app/FragmentManager_OnBackStackChangedListenerImplementor.java | Java | mit | 1,608 |
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Support for exporting actuator metrics to a simple in-memory store.
*/
package org.springframework.boot.actuate.autoconfigure.metrics.export.simple;
| tiarebalbi/spring-boot | spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/package-info.java | Java | apache-2.0 | 780 |
/*
* 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.checkpoint;
import java.io.Serializable;
/**
* Encapsulates all the meta data for a checkpoint.
*/
public class CheckpointMetaData implements Serializable {
private static final long serialVersionUID = -2387652345781312442L;
/** The ID of the checkpoint */
private final long checkpointId;
/** The timestamp of the checkpoint */
private final long timestamp;
public CheckpointMetaData(long checkpointId, long timestamp) {
this.checkpointId = checkpointId;
this.timestamp = timestamp;
}
public long getCheckpointId() {
return checkpointId;
}
public long getTimestamp() {
return timestamp;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CheckpointMetaData that = (CheckpointMetaData) o;
return (checkpointId == that.checkpointId)
&& (timestamp == that.timestamp);
}
@Override
public int hashCode() {
int result = (int) (checkpointId ^ (checkpointId >>> 32));
result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
return result;
}
@Override
public String toString() {
return "CheckpointMetaData{" +
"checkpointId=" + checkpointId +
", timestamp=" + timestamp +
'}';
}
}
| oscarceballos/flink-1.3.2 | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointMetaData.java | Java | apache-2.0 | 2,091 |
/*
* Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf;
import javax.swing.ComponentInputMap;
import javax.swing.JComponent;
/**
* A subclass of javax.swing.ComponentInputMap that implements UIResource.
* UI classes which provide a ComponentInputMap should use this class.
*
* @author Scott Violet
* @since 1.3
*/
@SuppressWarnings("serial") // Superclass is not serializable across versions
public class ComponentInputMapUIResource extends ComponentInputMap implements UIResource {
/**
* Constructs a {@code ComponentInputMapUIResource}.
* @param component a non-null JComponent
*/
public ComponentInputMapUIResource(JComponent component) {
super(component);
}
}
| FauxFaux/jdk9-jdk | src/java.desktop/share/classes/javax/swing/plaf/ComponentInputMapUIResource.java | Java | gpl-2.0 | 1,892 |
package ic2.api.tile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
/**
* Allows a tile entity to make use of the wrench's removal and rotation functions.
*/
public interface IWrenchable {
/**
* Determine if the wrench can be used to set the block's facing.
* Called before wrenchCanRemove().
*
* @param entityPlayer player using the wrench, may be null
* @param side block's side the wrench was clicked on
* @return Whether the wrenching was done and the wrench should be damaged
*/
boolean wrenchCanSetFacing(EntityPlayer entityPlayer, int side);
/**
* Get the block's facing.
*
* @return Block facing
*/
short getFacing();
/**
* Set the block's facing
*
* @param facing facing to set the block to
*/
void setFacing(short facing);
/**
* Determine if the wrench can be used to remove the block.
* Called if wrenchSetFacing fails.
*
* @param entityPlayer player using the wrench, may be null
* @return Whether the wrenching was done and the wrench should be damaged
*/
boolean wrenchCanRemove(EntityPlayer entityPlayer);
/**
* Determine the probability to drop the block as it is.
* The first entry in getDrops will be replaced by blockid:meta if the drop is successful.
*
* @return Probability from 0 to 1
*/
float getWrenchDropRate();
/**
* Determine the item the block will drop when the wrenching is successful.
*
* The ItemStack will be copied before creating the EntityItem.
*
* @param entityPlayer player using the wrench, may be null
* @return ItemStack to drop, may be null
*/
ItemStack getWrenchDrop(EntityPlayer entityPlayer);
}
| EacMods/Eac | src/main/java/ic2/api/tile/IWrenchable.java | Java | gpl-3.0 | 1,674 |
/*
* 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.tempuri.complex.data.arrays;
import java.math.BigDecimal;
public class ArrayOfNullableOfdecimal {
protected BigDecimal[] decimal;
public BigDecimal[] getDecimal() {
if (decimal == null) {
decimal = new BigDecimal[0];
}
return this.decimal;
}
public void setDecimal(BigDecimal[] decimal) {
this.decimal = decimal;
}
}
| arunasujith/wso2-axis2 | modules/integration/test/org/tempuri/complex/data/arrays/ArrayOfNullableOfdecimal.java | Java | apache-2.0 | 1,201 |
// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.impala.analysis;
import com.cloudera.impala.catalog.Db;
import com.cloudera.impala.catalog.Function;
import com.cloudera.impala.catalog.Function.CompareMode;
import com.cloudera.impala.catalog.ScalarFunction;
import com.cloudera.impala.catalog.ScalarType;
import com.cloudera.impala.catalog.Table;
import com.cloudera.impala.catalog.Type;
import com.cloudera.impala.common.AnalysisException;
import com.cloudera.impala.common.Reference;
import com.cloudera.impala.thrift.TExprNode;
import com.cloudera.impala.thrift.TExprNodeType;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class IsNullPredicate extends Predicate {
private final boolean isNotNull_;
private static final String IS_NULL = "is_null_pred";
private static final String IS_NOT_NULL = "is_not_null_pred";
public IsNullPredicate(Expr e, boolean isNotNull) {
super();
this.isNotNull_ = isNotNull;
Preconditions.checkNotNull(e);
children_.add(e);
}
/**
* Copy c'tor used in clone().
*/
protected IsNullPredicate(IsNullPredicate other) {
super(other);
isNotNull_ = other.isNotNull_;
}
public boolean isNotNull() { return isNotNull_; }
public static void initBuiltins(Db db) {
for (Type t: Type.getSupportedTypes()) {
if (t.isNull()) continue;
String isNullSymbol;
if (t.isBoolean()) {
isNullSymbol = "_ZN6impala15IsNullPredicate6IsNullIN10impala_udf10BooleanValE" +
"EES3_PNS2_15FunctionContextERKT_";
} else {
String udfType = Function.getUdfType(t);
isNullSymbol = "_ZN6impala15IsNullPredicate6IsNullIN10impala_udf" +
udfType.length() + udfType +
"EEENS2_10BooleanValEPNS2_15FunctionContextERKT_";
}
db.addBuiltin(ScalarFunction.createBuiltinOperator(
IS_NULL, isNullSymbol, Lists.newArrayList(t), Type.BOOLEAN));
String isNotNullSymbol = isNullSymbol.replace("6IsNull", "9IsNotNull");
db.addBuiltin(ScalarFunction.createBuiltinOperator(
IS_NOT_NULL, isNotNullSymbol, Lists.newArrayList(t), Type.BOOLEAN));
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) return false;
return ((IsNullPredicate) obj).isNotNull_ == isNotNull_;
}
@Override
public String toSqlImpl() {
return getChild(0).toSql() + (isNotNull_ ? " IS NOT NULL" : " IS NULL");
}
@Override
public String debugString() {
return Objects.toStringHelper(this)
.add("notNull", isNotNull_)
.addValue(super.debugString())
.toString();
}
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
if (isAnalyzed_) return;
super.analyze(analyzer);
if (contains(Subquery.class)) {
if (getChild(0) instanceof ExistsPredicate) {
// Replace the EXISTS subquery with a BoolLiteral as it can never return
// a null value.
setChild(0, new BoolLiteral(true));
getChild(0).analyze(analyzer);
} else if (!getChild(0).contains(Expr.IS_SCALAR_SUBQUERY)) {
// We only support scalar subqueries in an IS NULL predicate because
// they can be rewritten into a join.
// TODO: Add support for InPredicates and BinaryPredicates with
// subqueries when we implement independent subquery evaluation.
// TODO: Handle arbitrary UDA/Udfs
throw new AnalysisException("Unsupported IS NULL predicate that contains " +
"a subquery: " + toSqlImpl());
}
}
// Make sure the BE never sees TYPE_NULL
if (getChild(0).getType().isNull()) {
uncheckedCastChild(ScalarType.BOOLEAN, 0);
}
if (isNotNull_) {
fn_ = getBuiltinFunction(
analyzer, IS_NOT_NULL, collectChildReturnTypes(), CompareMode.IS_IDENTICAL);
} else {
fn_ = getBuiltinFunction(
analyzer, IS_NULL, collectChildReturnTypes(), CompareMode.IS_IDENTICAL);
}
// determine selectivity
// TODO: increase this to make sure we don't end up favoring broadcast joins
// due to underestimated cardinalities?
selectivity_ = DEFAULT_SELECTIVITY;
Reference<SlotRef> slotRefRef = new Reference<SlotRef>();
if (isSingleColumnPredicate(slotRefRef, null)) {
SlotDescriptor slotDesc = slotRefRef.getRef().getDesc();
if (!slotDesc.getStats().hasNulls()) return;
Table table = slotDesc.getParent().getTable();
if (table != null && table.getNumRows() > 0) {
long numRows = table.getNumRows();
if (isNotNull_) {
selectivity_ =
(double) (numRows - slotDesc.getStats().getNumNulls()) / (double) numRows;
} else {
selectivity_ = (double) slotDesc.getStats().getNumNulls() / (double) numRows;
}
selectivity_ = Math.max(0.0, Math.min(1.0, selectivity_));
}
}
}
@Override
protected void toThrift(TExprNode msg) {
msg.node_type = TExprNodeType.FUNCTION_CALL;
}
/*
* If predicate is of the form "<SlotRef> IS [NOT] NULL", returns the
* SlotRef.
*/
@Override
public SlotRef getBoundSlot() {
return getChild(0).unwrapSlotRef(true);
}
/**
* Negates an IsNullPredicate.
*/
@Override
public Expr negate() {
return new IsNullPredicate(getChild(0), !isNotNull_);
}
@Override
public Expr clone() { return new IsNullPredicate(this); }
}
| ImpalaToGo/ImpalaToGo | fe/src/main/java/com/cloudera/impala/analysis/IsNullPredicate.java | Java | apache-2.0 | 6,019 |
/*
* Copyright 2010 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.drools.core.command.runtime.process;
import javax.xml.bind.annotation.XmlRegistry;
@XmlRegistry
public class ObjectFactory {
public AbortWorkItemCommand createAbortWorkItemCommand() {
return new AbortWorkItemCommand();
}
public CompleteWorkItemCommand createCompleteWorkItemCommand() {
return new CompleteWorkItemCommand();
}
public CreateProcessInstanceCommand createCreateProcessInstanceCommand() {
return new CreateProcessInstanceCommand();
}
public SignalEventCommand createSignalEventCommand() {
return new SignalEventCommand();
}
public StartProcessCommand createStartProcessCommand() {
return new StartProcessCommand();
}
}
| rokn/Count_Words_2015 | testing/drools-master/drools-core/src/main/java/org/drools/core/command/runtime/process/ObjectFactory.java | Java | mit | 1,367 |
package org.thoughtcrime.securesms.database.loaders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
public class CountryListLoader extends AsyncTaskLoader<ArrayList<Map<String, String>>> {
public CountryListLoader(Context context) {
super(context);
}
@Override
public ArrayList<Map<String, String>> loadInBackground() {
Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
for (String region : regions) {
Map<String, String> data = new HashMap<String, String>(2);
data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
data.put("country_code", "+" +PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
results.add(data);
}
Collections.sort(results, new RegionComparator());
return results;
}
private class RegionComparator implements Comparator<Map<String, String>> {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
return lhs.get("country_name").compareTo(rhs.get("country_name"));
}
}
}
| metaplinius/TextSecure | src/org/thoughtcrime/securesms/database/loaders/CountryListLoader.java | Java | gpl-3.0 | 1,499 |
/*
*
* 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.wso2.andes.management.ui.views;
import static org.wso2.andes.management.ui.Constants.*;
import org.wso2.andes.management.ui.ApplicationRegistry;
import org.wso2.andes.management.ui.ManagedBean;
import org.wso2.andes.management.ui.jmx.MBeanUtility;
import org.wso2.andes.management.ui.model.AttributeData;
import org.wso2.andes.management.ui.model.ManagedAttributeModel;
import org.eclipse.jface.viewers.IColorProvider;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
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.TabFolder;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
/**
* Creates controller composite for the attribute's tab.
* @author Bhupendra Bhardwaj
*/
public class AttributesTabControl extends TabControl
{
private FormToolkit _toolkit;
private ScrolledForm _form;
private Table _table = null;
private TableViewer _tableViewer = null;
private int[] tableWidths = new int[] {275, 275};
private Composite _tableComposite = null;
private Composite _buttonsComposite = null;
private DisposeListener tableDisposeListener = new DisposeListenerImpl();
final Image image;
private Button _detailsButton = null;
private Button _editButton = null;
private Button _graphButton = null;
private boolean disableEditing = false;
private static final String MAX_VALUE = "MaxValue";
private static final String GRAPH_VALUES = "GraphValues";
private int GRAPH_WIDTH = 700;
private int GRAPH_HEIGHT = 450;
private int GRAPH_ITEM_GAP = 100;
private int startX = 80;
private int startY = 60;
public AttributesTabControl(TabFolder tabFolder)
{
super(tabFolder);
_toolkit = new FormToolkit(_tabFolder.getDisplay());
_form = _toolkit.createScrolledForm(_tabFolder);
GridLayout gridLayout = new GridLayout(2, false);
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
_form.getBody().setLayout(gridLayout);
_tableComposite = _toolkit.createComposite(_form.getBody());
_tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
_tableComposite.setLayout(new GridLayout());
_buttonsComposite = _toolkit.createComposite(_form.getBody());
_buttonsComposite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
_buttonsComposite.setLayout(new GridLayout());
image = Display.getCurrent().getSystemImage(SWT.ICON_INFORMATION);
createWidgets();
}
/**
* @see TabControl#getControl()
*/
public Control getControl()
{
return _form;
}
/**
* Creates required widgets for Attribute's tab
*/
protected void createWidgets()
{
createTable();
createTableViewer();
createButtons();
addTableListeners();
}
/**
* Creates table for listing the MBean attributes
*/
private void createTable()
{
_table = _toolkit.createTable(_tableComposite, SWT.FULL_SELECTION);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
_table.setLayoutData(gridData);
for (int i = 0; i < ATTRIBUTE_TABLE_TITLES.size(); ++i)
{
final TableColumn column = new TableColumn(_table, SWT.NONE);
column.setText(ATTRIBUTE_TABLE_TITLES.get(i));
column.setWidth(tableWidths[i]);
column.setResizable(true);
}
_table.setLinesVisible (true);
_table.setHeaderVisible (true);
}
/**
* Creates tableviewer for the attribute's table
*/
private void createTableViewer()
{
_tableViewer = new TableViewer(_table);
_tableViewer.setUseHashlookup(true);
_tableViewer.setColumnProperties(
ATTRIBUTE_TABLE_TITLES.toArray(new String[ATTRIBUTE_TABLE_TITLES.size()]));
_tableViewer.setContentProvider(new ContentProviderImpl());
_tableViewer.setLabelProvider(new LabelProviderImpl());
_tableViewer.setSorter(new ViewerSorterImpl());
}
private void createButtons()
{
addDetailsButton();
addEditButton();
addGraphButton();
}
private void addDetailsButton()
{
// Create and configure the button for attribute details
_detailsButton = _toolkit.createButton(_buttonsComposite, BUTTON_DETAILS, SWT.PUSH | SWT.CENTER);
_detailsButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
GridData gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
gridData.widthHint = 80;
_detailsButton.setLayoutData(gridData);
_detailsButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
disableEditing = true;
int index = _table.getSelectionIndex();
TableItem item = _table.getItem(index);
createDetailsPopup((AttributeData)item.getData());
disableEditing = false;
setFocus();
}
});
}
/**
* Creates the button for editing attributes.
*/
private void addEditButton()
{
// Create and configure the button for editing attribute
_editButton = _toolkit.createButton(_buttonsComposite, BUTTON_EDIT_ATTRIBUTE, SWT.PUSH | SWT.CENTER);
_editButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
GridData gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
gridData.widthHint = 80;
_editButton.setLayoutData(gridData);
_editButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
int index = _table.getSelectionIndex();
TableItem item = _table.getItem(index);
createDetailsPopup((AttributeData)item.getData());
setFocus();
}
});
}
/**
* Creates the button for viewing Graphs
*/
private void addGraphButton()
{
_graphButton = _toolkit.createButton(_buttonsComposite, BUTTON_GRAPH, SWT.PUSH | SWT.CENTER);
_graphButton.setFont(ApplicationRegistry.getFont(FONT_BUTTON));
GridData gridData = new GridData(SWT.FILL, SWT.TOP, false, false);
gridData.widthHint = 80;
_graphButton.setLayoutData(gridData);
_graphButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
int selectionIndex = _table.getSelectionIndex();
AttributeData data = (AttributeData)_table.getItem(selectionIndex).getData();
createGraph(data);
setFocus();
}
});
}
private void addTableListeners()
{
_tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){
public void selectionChanged(SelectionChangedEvent evt)
{
IStructuredSelection ss = (IStructuredSelection)evt.getSelection();
checkForEnablingButtons((AttributeData)ss.getFirstElement());
}
});
MouseListenerImpl listener = new MouseListenerImpl();
_tableViewer.getTable().addMouseTrackListener(listener);
_tableViewer.getTable().addMouseMoveListener(listener);
_tableViewer.getTable().addMouseListener(listener);
_table.addDisposeListener(tableDisposeListener);
// _table is equal to _tableViewer.getControl()
_table.addListener(SWT.MeasureItem, new Listener() {
public void handleEvent(Event event)
{
event.height = event.gc.getFontMetrics().getHeight() * 3/2;
}
});
}
/**
* Listeners implementation class for showing table tooltip
* @author Bhupendra Bhardwaj
*/
private class MouseListenerImpl implements MouseTrackListener, MouseMoveListener, KeyListener, MouseListener
{
Shell tooltipShell = null;
Label tooltipLabel = null;
public void mouseHover(MouseEvent event)
{
TableItem item = _table.getItem (new Point (event.x, event.y));
if (item != null)
{
AttributeData data = (AttributeData)item.getData();
if (tooltipShell != null && !tooltipShell.isDisposed ()) tooltipShell.dispose ();
tooltipShell = new Shell(_table.getShell(), SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
tooltipShell.setBackground(event.display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
FillLayout layout = new FillLayout();
layout.marginWidth = 2;
tooltipShell.setLayout(layout);
tooltipLabel = new Label(tooltipShell, SWT.NONE);
tooltipLabel.setForeground(event.display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
tooltipLabel.setBackground(event.display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
tooltipLabel.setText(data.getDescription());
tooltipLabel.setData("_TABLEITEM", item);
tooltipLabel.addListener(SWT.MouseExit, tooltipLabelListener);
tooltipLabel.addListener(SWT.MouseDown, tooltipLabelListener);
Point size = tooltipShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
Rectangle rect = item.getBounds(0);
Point pt = _table.toDisplay(rect.x, rect.y);
tooltipShell.setBounds(pt.x, pt.y, size.x, size.y);
tooltipShell.setVisible(true);
}
}
public void mouseEnter(MouseEvent e)
{
}
public void mouseExit(MouseEvent e)
{
}
// MouseMoveListener implementation
public void mouseMove(MouseEvent event)
{
if (tooltipShell == null)
return;
tooltipShell.dispose();
tooltipShell = null;
tooltipLabel = null;
}
// KeyListener implementation
public void keyPressed(KeyEvent e)
{
if (tooltipShell == null)
return;
tooltipShell.dispose();
tooltipShell = null;
tooltipLabel = null;
}
public void keyReleased(KeyEvent e)
{
}
// MouseListener implementation
public void mouseDoubleClick(MouseEvent event)
{
if (tooltipShell != null)
{
tooltipShell.dispose();
tooltipShell = null;
tooltipLabel = null;
}
Table table = (Table)event.getSource();
int selectionIndex = table.getSelectionIndex();
AttributeData data = (AttributeData)table.getItem(selectionIndex).getData();
createDetailsPopup(data);
}
public void mouseDown(MouseEvent e)
{
if (tooltipShell != null)
{
tooltipShell.dispose();
tooltipShell = null;
tooltipLabel = null;
}
}
public void mouseUp(MouseEvent e)
{
}
} // end of MouseListenerImpl
/**
* Creates pop-up window for showing attribute details
* @param data - Selectes attribute
*/
public void createDetailsPopup(AttributeData data)
{
int width = 500;
int height = 250;
if (!isSimpleType(data.getValue()))
{
width = 650;
height = 450;
}
Display display = Display.getCurrent();
Shell shell = ViewUtility.createPopupShell(ATTRIBUTE, width, height);
createDetailsPopupContents(shell, data);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
shell.dispose();
}
/**
* Listener class for table tooltip label
*/
final Listener tooltipLabelListener = new Listener ()
{
public void handleEvent (Event event)
{
Label label = (Label)event.widget;
Shell shell = label.getShell();
switch (event.type)
{
case SWT.MouseDown:
Event e = new Event();
e.item = (TableItem)label.getData ("_TABLEITEM");
_table.setSelection(new TableItem[] {(TableItem)e.item});
shell.dispose();
_table.setFocus();
break;
case SWT.MouseExit:
shell.dispose();
break;
}
}
};
/**
* Create the contents for the attribute details window pop-up
* @param shell - The shell that will be filled with details.
* @param attribute - Selected attribute
*/
private void createDetailsPopupContents(Composite shell, AttributeData attribute)
{
GridLayout layout = new GridLayout(2, false);
layout.horizontalSpacing = 10;
layout.verticalSpacing = 10;
layout.marginHeight = 20;
layout.marginWidth = 20;
Composite parent = _toolkit.createComposite(shell, SWT.NONE);
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
parent.setLayout(layout);
// Name
Label label = _toolkit.createLabel(parent, ATTRIBUTE_TABLE_TITLES.get(0), SWT.NONE);
GridData layoutData = new GridData(SWT.TRAIL, SWT.TOP, false, false);
label.setLayoutData(layoutData);
int textStyle = SWT.BEGINNING | SWT.BORDER |SWT.READ_ONLY;
Text value = _toolkit.createText(parent, ViewUtility.getDisplayText(attribute.getName()), textStyle);
value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
// Description
label = _toolkit.createLabel(parent, DESCRIPTION, SWT.NONE);
label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
value = _toolkit.createText(parent, attribute.getDescription(), textStyle);
value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
// value
label = _toolkit.createLabel(parent, ATTRIBUTE_TABLE_TITLES.get(1), SWT.NONE);
label.setLayoutData(new GridData(SWT.TRAIL, SWT.TOP, false, false));
if (!attribute.isReadable())
{
value = _toolkit.createText(parent, "", textStyle);
value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
}
else
{
if (!isSimpleType(attribute.getValue()))
{
if (attribute.getValue() instanceof String[])
{
String result = "";
for(String val : (String[]) attribute.getValue()){
result = result.concat(val+ "; ");
}
value = _toolkit.createText(parent, "", textStyle);
value.setText(result);
value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
}
else
{
Composite composite = new Composite(parent, SWT.BORDER);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
ViewUtility.populateCompositeWithData(_toolkit, composite, attribute.getValue());
}
}
else
{
if (attribute.isWritable())
{
value = _toolkit.createText(parent, "", SWT.BEGINNING | SWT.BORDER);
if(attribute.isNumber())
{
value.addVerifyListener(new NumberVerifyListener());
}
// set data to access in the listener
parent.setData(attribute);
}
else
{
value = _toolkit.createText(parent, "", textStyle);
}
value.setText(attribute.getValue().toString());
value.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
}
}
// Update button
Button updateButton = addUpdateButton(parent);
updateButton.setData(value);
if (!attribute.isWritable())
{
updateButton.setVisible(false);
}
if (disableEditing)
{
value.setEditable(false);
updateButton.setVisible(false);
}
}
/**
* Create the button for updating attributes. This should be enabled for writable attribute
*/
private Button addUpdateButton(Composite parent)
{
final Button updateButton = new Button(parent, SWT.PUSH | SWT.CENTER);
// set the data to access in the listener
parent.setData(BUTTON_UPDATE, updateButton);
updateButton.setText(BUTTON_UPDATE);
GridData gridData = new GridData (SWT.CENTER, SWT.BOTTOM, true, true, 2, 1);
gridData.widthHint = 100;
updateButton.setLayoutData(gridData);
updateButton.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
try
{
Button button = (Button)event.widget;
Text text = (Text)button.getData();
AttributeData data = (AttributeData)button.getParent().getData();
MBeanUtility.updateAttribute(_mbean, data, text.getText());
button.getShell().close();
refresh(_mbean);
}
catch (Exception ex)
{
MBeanUtility.handleException(_mbean, ex);
}
}
});
return updateButton;
}
/**
* Refreshes the attribute tab by querying the mbean server for latest values
*/
@Override
public void refresh(ManagedBean mbean)
{
_mbean = mbean;
if (_mbean == null)
{
_tableViewer.setInput(null);
return;
}
ManagedAttributeModel attributesList = null;
try
{
attributesList = MBeanUtility.getAttributes(mbean);
}
catch(Exception ex)
{
MBeanUtility.handleException(_mbean, ex);
}
_tableViewer.setInput(attributesList);
checkForEnablingButtons(getSelectionAttribute());
_form.layout(true);
_form.getBody().layout(true, true);
}
/**
* @see TabControl#setFocus()
*/
public void setFocus()
{
_table.setFocus();
}
/**
* Checks which buttons are to be enabled or disabled. The graph button will be enabled only
* for readable number attributes. Editing is enabled for writeable attribtues.
* @param attribute
*/
private void checkForEnablingButtons(AttributeData attribute)
{
if (attribute == null)
{
_detailsButton.setEnabled(false);
_editButton.setEnabled(false);
_graphButton.setEnabled(false);
return;
}
_detailsButton.setEnabled(true);
if (attribute.isWritable())
{
_editButton.setEnabled(true);
_graphButton.setEnabled(false);
}
else
{
_editButton.setEnabled(false);
// Currently only Queues are having attributes, which are suitable for a graph
if (attribute.isNumber() && _mbean.isQueue())
{
_graphButton.setEnabled(true);
}
else
{
_graphButton.setEnabled(false);
}
}
}
/**
* Creates graph in a pop-up window for given attribute.
* @param data
*/
private void createGraph(final AttributeData data)
{
Display display = Display.getCurrent();
Shell shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX);
shell.setText(_mbean.getName());
int x = display.getBounds().width;
int y = display.getBounds().height;
shell.setBounds(x/4, y/4, GRAPH_WIDTH, GRAPH_HEIGHT);
shell.setLayout(new FillLayout());
final Canvas canvas = new Canvas(shell, SWT.NONE);
long currentValue = Long.parseLong(data.getValue().toString());
long mValue = getGraphMaxValue(currentValue);
canvas.setData(MAX_VALUE, mValue);
canvas.setData(GRAPH_VALUES, new long[] {0,0,0,0,0,currentValue});
canvas.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
canvas.addPaintListener(new PaintListener()
{
public void paintControl(PaintEvent event)
{
Canvas canvas = (Canvas)event.widget;
int maxX = canvas.getSize().x;
int maxY = canvas.getSize().y;
event.gc.fillRectangle(canvas.getBounds());
event.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
event.gc.setLineWidth(4);
Object canvasData = canvas.getData(MAX_VALUE);
String str = canvasData.toString();
long maxValue = Long.parseLong(str);
// Set the graph dimensions
event.gc.drawText("0", startX - 40, maxY - startY - 10);
event.gc.drawText("" + maxValue/2, startX - 40, maxY/2);
event.gc.drawText("" + maxValue, startX - 40, startY);
// horizontal line
event.gc.drawLine(startX, maxY - startY, maxX - 60, maxY - startY);
// vertical line
event.gc.drawLine(startX, maxY - startY, startX, startY);
// set graph text
event.gc.drawText(data.getName(), startX - 40, startY - 40);
event.gc.drawText("25 sec", startX, maxY - startY + 10);
event.gc.drawText("20 sec", startX + GRAPH_ITEM_GAP, maxY - startY + 10);
event.gc.drawText("15 sec", startX + GRAPH_ITEM_GAP * 2, maxY - startY + 10);
event.gc.drawText("10 sec", startX + GRAPH_ITEM_GAP * 3, maxY - startY + 10);
event.gc.drawText(" 5 sec", startX + GRAPH_ITEM_GAP * 4, maxY - startY + 10);
event.gc.drawText(" 0 sec", startX + GRAPH_ITEM_GAP * 5, maxY - startY + 10);
// plot the graph now for values
event.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLUE));
canvasData = canvas.getData(GRAPH_VALUES);
long[] graphValues = (long[]) canvasData;
for (int i = 0; i < graphValues.length; i++)
{
int x = startX + i * GRAPH_ITEM_GAP;
int yTotalLength = (maxY - 2 * startY);
float ratio = ((float)graphValues[i]/(float)maxValue);
int itemlength = (int)(yTotalLength * ratio);
int y = maxY - startY - itemlength;
event.gc.drawLine(x, maxY- startY, x, y);
event.gc.drawText(String.valueOf(graphValues[i]), x, y - 20);
}
}
});
shell.open();
// Set up the timer for the animation
Runnable runnable = new Runnable()
{
public void run()
{
try
{
animate(canvas, data);
Display.getCurrent().timerExec(TIMER_INTERVAL, this);
}
catch(Exception ex)
{
MBeanUtility.handleException(ex);
}
}
};
// Launch the timer
display.timerExec(TIMER_INTERVAL, runnable);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
// Kill the timer
display.timerExec(-1, runnable);
shell.dispose();
}
/**
* @return selected attribute in the table
*/
public AttributeData getSelectionAttribute()
{
int index = _table.getSelectionIndex();
if (index == -1)
return null;
return (AttributeData)_table.getItem(index).getData();
}
/**
* checks for newer values of selected attribute to update the graph
* @param canvas
* @param data
* @throws Exception
*/
private void animate(Canvas canvas, AttributeData data) throws Exception
{
String attribute = data.getName();
Object valueObj = MBeanUtility.refreshAttribute(_mbean, attribute);
int value = Integer.parseInt(String.valueOf(valueObj));
Object canvasData = canvas.getData(GRAPH_VALUES);
long[] graphValues = (long[]) canvasData;
for (int i = 0; i < graphValues.length -1; i++)
{
graphValues[i] = graphValues[i + 1];
}
graphValues[graphValues.length - 1] = value;
canvasData = canvas.getData(MAX_VALUE);
long maxValue = Long.parseLong(String.valueOf(canvasData));
if (maxValue < value)
{
maxValue = getGraphMaxValue(value);
canvas.setData(MAX_VALUE, maxValue);
}
canvas.redraw();
}
/**
* @param maxAttributeValue
* @return dynamically calculated value for y-axis on the graph
*/
private long getGraphMaxValue(long maxAttributeValue)
{
long maxGraphValue = 100;
long temp = maxAttributeValue * 3/2;
if (temp > maxGraphValue)
{
long modulus = temp % 100;
maxGraphValue = temp + ( 100 - modulus);
}
return maxGraphValue;
}
/**
* Content Provider class for the table viewer
* @author Bhupendra Bhardwaj
*/
private static class ContentProviderImpl implements IStructuredContentProvider
{
public void inputChanged(Viewer v, Object oldInput, Object newInput)
{
}
public void dispose()
{
}
public Object[] getElements(Object parent)
{
return ((ManagedAttributeModel)parent).getAttributes();
}
}
/**
* Label Provider class for the table viewer
* @author Bhupendra Bhardwaj
*/
private class LabelProviderImpl extends LabelProvider implements ITableLabelProvider,
IFontProvider,
IColorProvider
{
AttributeData attribute = null;
public String getColumnText(Object element, int columnIndex)
{
String result = "";
attribute = (AttributeData) element;
switch (columnIndex)
{
case 0 : // attribute name column
result = ViewUtility.getDisplayText(attribute.getName());
break;
case 1 : // attribute value column
if (attribute.getValue() != null)
if (attribute.getValue() instanceof String[])
{
for(String val : (String[]) attribute.getValue()){
result = result.concat(val+ "; ");
}
}
else
{
result = String.valueOf(attribute.getValue());
}
break;
default :
result = "";
}
return result;
}
public Image getColumnImage(Object element, int columnIndex)
{
return null;
}
public Font getFont(Object element)
{
return ApplicationRegistry.getFont(FONT_TABLE_CELL);
}
public Color getForeground(Object element)
{
attribute = (AttributeData) element;
if (attribute.isWritable())
return Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
else
return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
}
public Color getBackground(Object element)
{
return _form.getBackground();
}
}
private static class DisposeListenerImpl implements DisposeListener
{
public void widgetDisposed(DisposeEvent e)
{
}
}
/**
* Sorter class for the table viewer. It sorts the table for according to attribute name.
* @author Bhupendra Bhardwaj
*
*/
private static class ViewerSorterImpl extends ViewerSorter
{
public int compare(Viewer viewer, Object o1, Object o2)
{
AttributeData attribtue1 = (AttributeData)o1;
AttributeData attribtue2 = (AttributeData)o2;
return collator.compare(attribtue1.getName(), attribtue2.getName());
}
}
}
| pamod/andes | modules/andes-core/management/eclipse-plugin/src/main/java/org/wso2/andes/management/ui/views/AttributesTabControl.java | Java | apache-2.0 | 33,397 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2018 by Hitachi Vantara : 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.core.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.Const;
import org.pentaho.di.ui.core.FormDataBuilder;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import java.util.HashMap;
import java.util.Map;
/**
* A base dialog class containing a body and a configurable button panel.
*/
public abstract class BaseDialog extends Dialog {
public static final int MARGIN_SIZE = 15;
public static final int LABEL_SPACING = 5;
public static final int ELEMENT_SPACING = 10;
public static final int MEDIUM_FIELD = 250;
public static final int MEDIUM_SMALL_FIELD = 150;
public static final int SMALL_FIELD = 50;
public static final int SHELL_WIDTH_OFFSET = 16;
public static final int VAR_ICON_WIDTH = GUIResource.getInstance().getImageVariable().getBounds().width;
public static final int VAR_ICON_HEIGHT = GUIResource.getInstance().getImageVariable().getBounds().height;
protected Map<String, Listener> buttons = new HashMap();
protected Shell shell;
protected PropsUI props;
protected int width = -1;
protected String title;
private int footerTopPadding = BaseDialog.ELEMENT_SPACING * 4;
public BaseDialog( final Shell shell ) {
this( shell, null, -1 );
}
public BaseDialog( final Shell shell, final String title, final int width ) {
super( shell, SWT.NONE );
this.props = PropsUI.getInstance();
this.title = title;
this.width = width;
}
/**
* Returns a {@link org.eclipse.swt.events.SelectionAdapter} that is used to "submit" the dialog.
*/
private Display prepareLayout() {
// Prep the parent shell and the dialog shell
final Shell parent = getParent();
final Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.SHEET );
shell.setImage( GUIResource.getInstance().getImageSpoon() );
props.setLook( shell );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
@Override
public void shellClosed( ShellEvent e ) {
dispose();
}
} );
final FormLayout formLayout = new FormLayout();
formLayout.marginWidth = MARGIN_SIZE;
formLayout.marginHeight = MARGIN_SIZE;
shell.setLayout( formLayout );
shell.setText( this.title );
return display;
}
/**
* Returns the last element in the body - the one to which the buttons should be attached.
*
* @return
*/
protected abstract Control buildBody();
public int open() {
final Display display = prepareLayout();
final Control lastBodyElement = buildBody();
buildFooter( lastBodyElement );
open( display );
return 1;
}
private void open( final Display display ) {
shell.pack();
if ( width > 0 ) {
final int height = shell.computeSize( width, SWT.DEFAULT ).y;
// for some reason the actual width and minimum width are smaller than what is requested - add the
// SHELL_WIDTH_OFFSET to get the desired size
shell.setMinimumSize( width + SHELL_WIDTH_OFFSET, height );
shell.setSize( width + SHELL_WIDTH_OFFSET, height );
}
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
}
protected void buildFooter( final Control anchorElement ) {
final Button[] buttonArr = new Button[ buttons == null ? 0 : buttons.size() ];
int index = 0;
if ( buttons != null ) {
for ( final String buttonName : buttons.keySet() ) {
final Button button = new Button( shell, SWT.PUSH );
button.setText( buttonName );
final Listener listener = buttons.get( buttonName );
if ( listener != null ) {
button.addListener( SWT.Selection, listener );
} else {
// fall back on simply closing the dialog
button.addListener( SWT.Selection, event -> {
dispose();
} );
}
buttonArr[ index++ ] = button;
}
}
// traverse the buttons backwards to position them to the right
Button previousButton = null;
for ( int i = buttonArr.length - 1; i >= 0; i-- ) {
final Button button = buttonArr[ i ];
if ( previousButton == null ) {
button.setLayoutData( new FormDataBuilder().top(
anchorElement, footerTopPadding ).right( 100, 0 ).result() );
} else {
button.setLayoutData( new FormDataBuilder().top( anchorElement, footerTopPadding ).right(
previousButton, Const.isOSX() ? 0 : -BaseDialog.LABEL_SPACING ).result() );
}
previousButton = button;
}
}
public void setFooterTopPadding( final int footerTopPadding ) {
this.footerTopPadding = footerTopPadding;
}
public void dispose() {
props.setScreen( new WindowProperty( shell ) );
shell.dispose();
}
public void setButtons( final Map<String, Listener> buttons ) {
this.buttons = buttons;
}
}
| tkafalas/pentaho-kettle | ui/src/main/java/org/pentaho/di/ui/core/dialog/BaseDialog.java | Java | apache-2.0 | 6,332 |
/**
* Copyright (c) 2006-2018 The Apereo Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/ecl2
*
* 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.sakaiproject.sitestats.api.event.detailed.news;
import org.sakaiproject.sitestats.api.event.detailed.ResolvedEventData;
/**
* Data for a news (rss) feed
* @author plukasew
*/
public class FeedData implements ResolvedEventData
{
public final String title;
/**
* Constructor
* @param title the title of the feed
*/
public FeedData(String title)
{
this.title = title;
}
}
| OpenCollabZA/sakai | sitestats/sitestats-api/src/java/org/sakaiproject/sitestats/api/event/detailed/news/FeedData.java | Java | apache-2.0 | 1,031 |
/*
* #%L
* BroadleafCommerce Integration
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* 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 org.broadleafcommerce.profile.dataprovider;
import org.broadleafcommerce.profile.core.domain.Phone;
import org.broadleafcommerce.profile.core.domain.PhoneImpl;
import org.testng.annotations.DataProvider;
public class PhoneDataProvider {
@DataProvider(name = "setupPhone")
public static Object[][] createPhone() {
Phone phone = new PhoneImpl();
phone.setPhoneNumber("999-999-9999");
return new Object[][] { new Object[] { phone } };
}
}
| cloudbearings/BroadleafCommerce | integration/src/test/java/org/broadleafcommerce/profile/dataprovider/PhoneDataProvider.java | Java | apache-2.0 | 1,157 |
package com.tutsplus.zoo.events;
/**
* Created by paulruiz on 4/8/15.
*/
public class DrawerSectionItemClickedEvent {
public String section;
public DrawerSectionItemClickedEvent( String section ) {
this.section = section;
}
}
| elamweaver/getting-started-with-android | Lesson 9 - Pulling Down Exhibit Data/app/src/main/java/com/tutsplus/zoo/events/DrawerSectionItemClickedEvent.java | Java | bsd-2-clause | 251 |
/**
* Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) 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
*/
package org.eclipse.smarthome.core.thing.dto;
import java.util.List;
/**
* This is a data transfer object that is used to serialize channel group definitions.
*
* @author Dennis Nobel - Initial contribution
*/
public class ChannelGroupDefinitionDTO {
public String id;
public String description;
public String label;
public List<ChannelDefinitionDTO> channels;
public ChannelGroupDefinitionDTO() {
}
public ChannelGroupDefinitionDTO(String id, String label, String description, List<ChannelDefinitionDTO> channels) {
this.id = id;
this.label = label;
this.description = description;
this.channels = channels;
}
}
| ibaton/smarthome | bundles/core/org.eclipse.smarthome.core.thing/src/main/java/org/eclipse/smarthome/core/thing/dto/ChannelGroupDefinitionDTO.java | Java | epl-1.0 | 1,008 |
/**
* Copyright (c) 2010-2016 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.epsonprojector.internal;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.epsonprojector.EpsonProjectorBindingProvider;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.AspectRatio;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.Background;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.Color;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.ColorMode;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.Gamma;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.Luminance;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.PowerStatus;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.Source;
import org.openhab.binding.epsonprojector.internal.EpsonProjectorDevice.Switch;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Binding which communicates with (one or many) Epson projectors.
*
*
* @author Pauli Anttila
* @since 1.3.0
*/
public class EpsonProjectorBinding extends AbstractActiveBinding<EpsonProjectorBindingProvider>
implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(EpsonProjectorBinding.class);
private final static int DEFAULT_PORT = 60128;
/**
* the interval to find new refresh candidates (defaults to 1000
* milliseconds)
*/
private int granularity = 1000;
private Map<String, Long> lastUpdateMap = new HashMap<String, Long>();
protected Map<String, DeviceConfig> deviceConfigCache = null;
/**
* RegEx to validate a config
* <code>'^(.*?)\\.(host|port|serialPort)$'</code>
*/
private static final Pattern EXTRACT_CONFIG_PATTERN = Pattern.compile("^(.*?)\\.(host|port|serialPort)$");
@Override
public void activate() {
logger.debug("Activate");
}
@Override
public void deactivate() {
logger.debug("Deactivate");
closeConnection();
}
private void closeConnection() {
if (deviceConfigCache != null) {
// close all connections
for (Entry<String, DeviceConfig> entry : deviceConfigCache.entrySet()) {
DeviceConfig deviceCfg = entry.getValue();
if (deviceCfg != null) {
EpsonProjectorDevice device = deviceCfg.getConnection();
if (device != null) {
try {
logger.debug("Closing connection to device '{}' ", deviceCfg.deviceId);
device.disconnect();
} catch (EpsonProjectorException e) {
logger.error("Error occured when closing connection to device '{}'", deviceCfg.deviceId);
}
}
}
}
deviceConfigCache = null;
}
}
/**
* @{inheritDoc
*/
@Override
protected long getRefreshInterval() {
return granularity;
}
/**
* @{inheritDoc
*/
@Override
protected String getName() {
return "Epson projector Refresh Service";
}
/**
* @{inheritDoc
*/
@Override
public void execute() {
for (EpsonProjectorBindingProvider provider : providers) {
for (String itemName : provider.getInBindingItemNames()) {
int refreshInterval = provider.getRefreshInterval(itemName);
Long lastUpdateTimeStamp = lastUpdateMap.get(itemName);
if (lastUpdateTimeStamp == null) {
lastUpdateTimeStamp = 0L;
}
long age = System.currentTimeMillis() - lastUpdateTimeStamp;
boolean needsUpdate = age >= refreshInterval;
if (needsUpdate) {
boolean refreshOnlyWhenPowerOn = provider.refreshOnlyWhenPowerOn(itemName);
String deviceId = provider.getDeviceId(itemName);
if (refreshOnlyWhenPowerOn) {
OnOffType state = (OnOffType) queryDataFromDevice(deviceId, EpsonProjectorCommandType.POWER,
SwitchItem.class);
if (state != OnOffType.ON) {
logger.debug("projector power is OFF, skip refresh for item '{}'", itemName);
lastUpdateMap.put(itemName, System.currentTimeMillis());
return;
}
}
logger.debug("item '{}' is about to be refreshed now", itemName);
EpsonProjectorCommandType commmandType = provider.getCommandType(itemName);
Class<? extends Item> itemType = provider.getItemType(itemName);
State state = queryDataFromDevice(deviceId, commmandType, itemType);
if (state != null) {
eventPublisher.postUpdate(itemName, state);
} else {
logger.error("No response received from command '{}'", commmandType);
}
lastUpdateMap.put(itemName, System.currentTimeMillis());
}
}
}
}
private State queryDataFromDevice(String deviceId, EpsonProjectorCommandType commmandType,
Class<? extends Item> itemType) {
DeviceConfig device = deviceConfigCache.get(deviceId);
if (device == null) {
logger.error("Could not find device '{}'", deviceId);
return null;
}
EpsonProjectorDevice remoteController = device.getConnection();
if (remoteController == null) {
logger.error("Could not find device '{}'", deviceId);
return null;
}
try {
if (remoteController.isConnected() == false) {
remoteController.connect();
}
switch (commmandType) {
case AKEYSTONE:
int autoKeystone = remoteController.getAutoKeystone();
return new DecimalType(autoKeystone);
case ASPECT_RATIO:
AspectRatio aspectRatio = remoteController.getAspectRatio();
return new StringType(aspectRatio.toString());
case BACKGROUND:
Background background = remoteController.getBackground();
return new StringType(background.toString());
case BRIGHTNESS:
int brightness = remoteController.getBrightness();
return new DecimalType(brightness);
case COLOR:
Color color = remoteController.getColor();
return new StringType(color.toString());
case COLOR_MODE:
ColorMode colorMode = remoteController.getColorMode();
return new StringType(colorMode.toString());
case COLOR_TEMP:
int ctemp = remoteController.getColorTemperature();
return new DecimalType(ctemp);
case CONTRAST:
int contrast = remoteController.getContrast();
return new DecimalType(contrast);
case DENSITY:
int density = remoteController.getDensity();
return new DecimalType(density);
case DIRECT_SOURCE:
int directSource = remoteController.getDirectSource();
return new DecimalType(directSource);
case ERR_CODE:
int err = remoteController.getError();
return new DecimalType(err);
case ERR_MESSAGE:
String errString = remoteController.getErrorString();
return new StringType(errString);
case FLESH_TEMP:
int fleshColor = remoteController.getFleshColor();
return new DecimalType(fleshColor);
case GAIN_BLUE:
int gainBlue = remoteController.getGainBlue();
return new DecimalType(gainBlue);
case GAIN_GREEN:
int gainGreen = remoteController.getGainGreen();
return new DecimalType(gainGreen);
case GAIN_RED:
int gainRed = remoteController.getGainRed();
return new DecimalType(gainRed);
case GAMMA:
Gamma gamma = remoteController.getGamma();
return new StringType(gamma.toString());
case GAMMA_STEP:
logger.warn("Get '{}' not implemented!", commmandType.toString());
return null;
case HKEYSTONE:
int hKeystone = remoteController.getHorizontalKeystone();
return new DecimalType(hKeystone);
case HPOSITION:
int hPosition = remoteController.getHorizontalPosition();
return new DecimalType(hPosition);
case HREVERSE:
Switch hReverse = remoteController.getHorizontalReverse();
return hReverse == Switch.ON ? OnOffType.ON : OnOffType.OFF;
case KEY_CODE:
break;
case LAMP_TIME:
int lampTime = remoteController.getLampTime();
return new DecimalType(lampTime);
case LUMINANCE:
Luminance luminance = remoteController.getLuminance();
return new StringType(luminance.toString());
case MUTE:
Switch mute = remoteController.getMute();
return mute == Switch.ON ? OnOffType.ON : OnOffType.OFF;
case OFFSET_BLUE:
int offsetBlue = remoteController.getOffsetBlue();
return new DecimalType(offsetBlue);
case OFFSET_GREEN:
int offsetGreen = remoteController.getOffsetGreen();
return new DecimalType(offsetGreen);
case OFFSET_RED:
int offsetRed = remoteController.getOffsetRed();
return new DecimalType(offsetRed);
case POWER:
PowerStatus powerStatus = remoteController.getPowerStatus();
if (powerStatus == PowerStatus.ON) {
return OnOffType.ON;
} else {
return OnOffType.OFF;
}
case POWER_STATE:
PowerStatus powerStatus1 = remoteController.getPowerStatus();
return new StringType(powerStatus1.toString());
case SHARP:
logger.warn("Get '{}' not implemented!", commmandType.toString());
return null;
case SOURCE:
Source source = remoteController.getSource();
return new StringType(source.toString());
case SYNC:
int sync = remoteController.getSync();
return new DecimalType(sync);
case TINT:
int tint = remoteController.getTint();
return new DecimalType(tint);
case TRACKING:
int tracking = remoteController.getTracking();
return new DecimalType(tracking);
case VKEYSTONE:
int vKeystone = remoteController.getVerticalKeystone();
return new DecimalType(vKeystone);
case VPOSITION:
int vPosition = remoteController.getVerticalPosition();
return new DecimalType(vPosition);
case VREVERSE:
Switch vReverse = remoteController.getVerticalReverse();
return vReverse == Switch.ON ? OnOffType.ON : OnOffType.OFF;
default:
logger.warn("Unknown '{}' command!", commmandType);
return null;
}
} catch (EpsonProjectorException e) {
logger.warn("Couldn't execute command '{}', {}", commmandType.toString(), e);
} catch (Exception e) {
logger.warn("Couldn't create state of type '{}'", itemType);
return null;
}
return null;
}
/**
* @{inheritDoc
*/
@Override
public void internalReceiveCommand(String itemName, Command command) {
EpsonProjectorBindingProvider provider = findFirstMatchingBindingProvider(itemName, command);
if (provider == null) {
logger.warn("doesn't find matching binding provider [itemName={}, command={}]", itemName, command);
return;
}
if (provider.isOutBinding(itemName)) {
EpsonProjectorCommandType commmandType = provider.getCommandType(itemName);
String deviceId = provider.getDeviceId(itemName);
if (commmandType != null) {
sendDataToDevice(deviceId, commmandType, command);
}
} else {
logger.warn("itemName={} is not out binding", itemName);
}
}
private void sendDataToDevice(String deviceId, EpsonProjectorCommandType commmandType, Command command) {
DeviceConfig device = deviceConfigCache.get(deviceId);
if (device == null) {
logger.error("Could not find device '{}'", deviceId);
return;
}
EpsonProjectorDevice remoteController = device.getConnection();
if (remoteController == null) {
logger.error("Could not find device '{}'", deviceId);
return;
}
try {
if (remoteController.isConnected() == false) {
remoteController.connect();
}
switch (commmandType) {
case AKEYSTONE:
remoteController.setAutoKeystone(((DecimalType) command).intValue());
break;
case ASPECT_RATIO:
remoteController.setAspectRatio(AspectRatio.valueOf(command.toString()));
break;
case BACKGROUND:
remoteController.setBackground(Background.valueOf(command.toString()));
break;
case BRIGHTNESS:
remoteController.setBrightness(((DecimalType) command).intValue());
break;
case COLOR:
remoteController.setColor(Color.valueOf(command.toString()));
break;
case COLOR_MODE:
remoteController.setColorMode(ColorMode.valueOf(command.toString()));
break;
case COLOR_TEMP:
remoteController.setColorTemperature(((DecimalType) command).intValue());
break;
case CONTRAST:
remoteController.setContrast(((DecimalType) command).intValue());
break;
case DENSITY:
remoteController.setDensity(((DecimalType) command).intValue());
break;
case DIRECT_SOURCE:
remoteController.setDirectSource(((DecimalType) command).intValue());
break;
case ERR_CODE:
logger.error("'{}' is read only parameter", commmandType);
break;
case ERR_MESSAGE:
logger.error("'{}' is read only parameter", commmandType);
break;
case FLESH_TEMP:
remoteController.setFleshColor(((DecimalType) command).intValue());
break;
case GAIN_BLUE:
remoteController.setGainBlue(((DecimalType) command).intValue());
break;
case GAIN_GREEN:
remoteController.setGainGreen(((DecimalType) command).intValue());
break;
case GAIN_RED:
remoteController.setGainRed(((DecimalType) command).intValue());
break;
case GAMMA:
remoteController.setGamma(Gamma.valueOf(command.toString()));
break;
case GAMMA_STEP:
logger.warn("Set '{}' not implemented!", commmandType.toString());
break;
case HKEYSTONE:
remoteController.setHorizontalKeystone(((DecimalType) command).intValue());
break;
case HPOSITION:
remoteController.setHorizontalPosition(((DecimalType) command).intValue());
break;
case HREVERSE:
remoteController.setHorizontalReverse((command == OnOffType.ON ? Switch.ON : Switch.OFF));
break;
case KEY_CODE:
remoteController.sendKeyCode(((DecimalType) command).intValue());
break;
case LAMP_TIME:
logger.error("'{}' is read only parameter", commmandType);
break;
case LUMINANCE:
remoteController.setLuminance(Luminance.valueOf(command.toString()));
break;
case MUTE:
remoteController.setMute((command == OnOffType.ON ? Switch.ON : Switch.OFF));
break;
case OFFSET_BLUE:
remoteController.setOffsetBlue(((DecimalType) command).intValue());
break;
case OFFSET_GREEN:
remoteController.setOffsetGreen(((DecimalType) command).intValue());
break;
case OFFSET_RED:
remoteController.setOffsetRed(((DecimalType) command).intValue());
break;
case POWER:
remoteController.setPower((command == OnOffType.ON ? Switch.ON : Switch.OFF));
break;
case POWER_STATE:
logger.error("'{}' is read only parameter", commmandType);
break;
case SHARP:
logger.warn("Set '{}' not implemented!", commmandType.toString());
break;
case SOURCE:
remoteController.setSource(Source.valueOf(command.toString()));
break;
case SYNC:
remoteController.setSync(((DecimalType) command).intValue());
break;
case TINT:
remoteController.setTint(((DecimalType) command).intValue());
break;
case TRACKING:
remoteController.setTracking(((DecimalType) command).intValue());
break;
case VKEYSTONE:
remoteController.setVerticalKeystone(((DecimalType) command).intValue());
break;
case VPOSITION:
remoteController.setVerticalPosition(((DecimalType) command).intValue());
break;
case VREVERSE:
remoteController.setVerticalReverse((command == OnOffType.ON ? Switch.ON : Switch.OFF));
break;
default:
logger.warn("Unknown '{}' command!", commmandType);
break;
}
} catch (EpsonProjectorException e) {
logger.error("Couldn't execute command '{}', {}", commmandType, e);
}
}
/**
* Find the first matching {@link ExecBindingProvider} according to
* <code>itemName</code> and <code>command</code>. If no direct match is
* found, a second match is issued with wilcard-command '*'.
*
* @param itemName
* @param command
*
* @return the matching binding provider or <code>null</code> if no binding
* provider could be found
*/
private EpsonProjectorBindingProvider findFirstMatchingBindingProvider(String itemName, Command command) {
EpsonProjectorBindingProvider firstMatchingProvider = null;
for (EpsonProjectorBindingProvider provider : this.providers) {
EpsonProjectorCommandType commmandType = provider.getCommandType(itemName);
if (commmandType != null) {
firstMatchingProvider = provider;
break;
}
}
return firstMatchingProvider;
}
protected void addBindingProvider(EpsonProjectorBindingProvider bindingProvider) {
super.addBindingProvider(bindingProvider);
}
protected void removeBindingProvider(EpsonProjectorBindingProvider bindingProvider) {
super.removeBindingProvider(bindingProvider);
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
logger.debug("Configuration updated, config {}", config != null ? true : false);
if (config != null) {
if (deviceConfigCache == null) {
deviceConfigCache = new HashMap<String, DeviceConfig>();
}
String granularityString = (String) config.get("granularity");
if (StringUtils.isNotBlank(granularityString)) {
granularity = Integer.parseInt(granularityString);
}
Enumeration<String> keys = config.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
// the config-key enumeration contains additional keys that we
// don't want to process here ...
if ("service.pid".equals(key)) {
continue;
}
Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);
if (!matcher.matches()) {
logger.warn(
"given config key '" + key + "' does not follow the expected pattern '<id>.<host|port>'");
continue;
}
matcher.reset();
matcher.find();
String deviceId = matcher.group(1);
DeviceConfig deviceConfig = deviceConfigCache.get(deviceId);
if (deviceConfig == null) {
logger.debug("Added new device {}", deviceId);
deviceConfig = new DeviceConfig(deviceId);
deviceConfigCache.put(deviceId, deviceConfig);
}
String configKey = matcher.group(2);
String value = (String) config.get(key);
if ("serialPort".equals(configKey)) {
deviceConfig.serialPort = value;
} else if ("host".equals(configKey)) {
deviceConfig.host = value;
} else if ("port".equals(configKey)) {
deviceConfig.port = Integer.valueOf(value);
} else {
throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
}
}
setProperlyConfigured(true);
}
}
/**
* Internal data structure which carries the connection details of one
* device (there could be several)
*/
static class DeviceConfig {
String deviceId;
String serialPort = null;
String host = null;
int port = DEFAULT_PORT;
EpsonProjectorDevice device = null;
public DeviceConfig(String deviceId) {
this.deviceId = deviceId;
}
@Override
public String toString() {
return "Device [id=" + deviceId + ", host=" + host + ", port=" + port + "]";
}
EpsonProjectorDevice getConnection() {
if (device == null) {
if (serialPort != null) {
device = new EpsonProjectorDevice(serialPort);
} else if (host != null) {
device = new EpsonProjectorDevice(host, port);
}
}
return device;
}
}
}
| mvolaart/openhab | bundles/binding/org.openhab.binding.epsonprojector/src/main/java/org/openhab/binding/epsonprojector/internal/EpsonProjectorBinding.java | Java | epl-1.0 | 25,678 |
/*
* Copyright 2012-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.springframework.boot.diagnostics.analyzer;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Proxy;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
import org.springframework.boot.diagnostics.FailureAnalysis;
/**
* An {@link AbstractFailureAnalyzer} that performs analysis of failures caused by a
* {@link BeanNotOfRequiredTypeException}.
*
* @author Andy Wilkinson
*/
public class BeanNotOfRequiredTypeFailureAnalyzer
extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
private static final String ACTION = "Consider injecting the bean as one of its "
+ "interfaces or forcing the use of CGLib-based "
+ "proxies by setting proxyTargetClass=true on @EnableAsync and/or "
+ "@EnableCaching.";
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
BeanNotOfRequiredTypeException cause) {
if (!Proxy.isProxyClass(cause.getActualType())) {
return null;
}
return new FailureAnalysis(getDescription(cause), ACTION, cause);
}
private String getDescription(BeanNotOfRequiredTypeException ex) {
StringWriter description = new StringWriter();
PrintWriter printer = new PrintWriter(description);
printer.printf(
"The bean '%s' could not be injected as a '%s' because it is a "
+ "JDK dynamic proxy that implements:%n",
ex.getBeanName(), ex.getRequiredType().getName());
for (Class<?> requiredTypeInterface : ex.getRequiredType().getInterfaces()) {
printer.println("\t" + requiredTypeInterface.getName());
}
return description.toString();
}
}
| xiaoleiPENG/my-project | spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzer.java | Java | apache-2.0 | 2,289 |
/*
* 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.sling.discovery.base.connectors.ping;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest;
import org.apache.sling.discovery.base.connectors.BaseConfig;
import org.junit.Before;
import org.junit.Test;
import junitx.util.PrivateAccessor;
public class TopologyConnectorServletTest {
private TopologyConnectorServlet servlet;
private HttpServletRequest getRequest(String host, String addr) {
HttpServletRequest result = mock(HttpServletRequest.class);
when(result.getRemoteAddr()).thenReturn(addr);
when(result.getRemoteHost()).thenReturn(host);
return result;
}
@Before
public void setUp() throws Exception {
servlet = new TopologyConnectorServlet();
BaseConfig config = mock(BaseConfig.class);
PrivateAccessor.setField(servlet, "config", config);
}
@Test
public void testNull() throws Exception {
servlet.initWhitelist(null); // should work fine
servlet.initWhitelist(new String[0]); // should also work fine
}
@Test
public void testPlaintextWhitelist_enabled() throws Exception {
servlet.initWhitelist(new String[] {"foo", "bar"});
assertTrue(servlet.isWhitelisted(getRequest("foo", "x")));
assertTrue(servlet.isWhitelisted(getRequest("bar", "x")));
assertTrue(servlet.isWhitelisted(getRequest("y", "foo")));
assertTrue(servlet.isWhitelisted(getRequest("y", "bar")));
}
@Test
public void testPlaintextWhitelist_disabled() throws Exception {
servlet.initWhitelist(new String[] {});
assertFalse(servlet.isWhitelisted(getRequest("foo", "x")));
assertFalse(servlet.isWhitelisted(getRequest("bar", "x")));
assertFalse(servlet.isWhitelisted(getRequest("y", "foo")));
assertFalse(servlet.isWhitelisted(getRequest("y", "bar")));
}
@Test
public void testWildcardWhitelist() throws Exception {
servlet.initWhitelist(new String[] {"foo*", "b?r", "test"});
assertTrue(servlet.isWhitelisted(getRequest("foo", "x")));
assertTrue(servlet.isWhitelisted(getRequest("fooo", "x")));
assertTrue(servlet.isWhitelisted(getRequest("foooo", "x")));
assertTrue(servlet.isWhitelisted(getRequest("x", "foo")));
assertTrue(servlet.isWhitelisted(getRequest("x", "fooo")));
assertTrue(servlet.isWhitelisted(getRequest("x", "foooo")));
assertTrue(servlet.isWhitelisted(getRequest("bur", "x")));
assertTrue(servlet.isWhitelisted(getRequest("x", "bur")));
assertTrue(servlet.isWhitelisted(getRequest("x", "test")));
assertFalse(servlet.isWhitelisted(getRequest("fo", "x")));
assertFalse(servlet.isWhitelisted(getRequest("x", "testy")));
}
@Test
public void testSubnetMaskWhitelist() throws Exception {
servlet.initWhitelist(new String[] {"1.2.3.4/24", "2.3.4.1/30", "3.4.5.6/31"});
assertTrue(servlet.isWhitelisted(getRequest("foo", "1.2.3.4")));
assertFalse(servlet.isWhitelisted(getRequest("1.2.3.4", "1.2.4.3")));
assertTrue(servlet.isWhitelisted(getRequest("foo", "1.2.3.1")));
assertTrue(servlet.isWhitelisted(getRequest("foo", "1.2.3.254")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "1.2.4.5")));
assertTrue(servlet.isWhitelisted(getRequest("foo", "2.3.4.1")));
assertTrue(servlet.isWhitelisted(getRequest("foo", "2.3.4.2")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "2.3.4.3")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "2.3.4.4")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.1")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.2")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.3")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.4")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.5")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.6")));
assertFalse(servlet.isWhitelisted(getRequest("foo", "3.4.5.7")));
}
}
| ieb/sling | bundles/extensions/discovery/base/src/test/java/org/apache/sling/discovery/base/connectors/ping/TopologyConnectorServletTest.java | Java | apache-2.0 | 5,117 |
/**
* 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.hdfs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.zip.CRC32;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.protocol.DirectoryListing;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
import org.apache.hadoop.hdfs.server.namenode.FSImageFormat;
import org.apache.hadoop.hdfs.server.namenode.FSImageTestUtil;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
/**
* This tests data transfer protocol handling in the Datanode. It sends
* various forms of wrong data and verifies that Datanode handles it well.
*
* This test uses the following items from src/test/.../dfs directory :
* 1) hadoop-22-dfs-dir.tgz and other tarred pre-upgrade NN / DN
* directory images
* 2) hadoop-dfs-dir.txt : checksums that are compared in this test.
* Please read hadoop-dfs-dir.txt for more information.
*/
public class TestDFSUpgradeFromImage {
private static final Log LOG = LogFactory
.getLog(TestDFSUpgradeFromImage.class);
private static final File TEST_ROOT_DIR =
new File(MiniDFSCluster.getBaseDirectory());
private static final String HADOOP_DFS_DIR_TXT = "hadoop-dfs-dir.txt";
private static final String HADOOP22_IMAGE = "hadoop-22-dfs-dir.tgz";
private static final String HADOOP1_BBW_IMAGE = "hadoop1-bbw.tgz";
private static final String HADOOP1_RESERVED_IMAGE = "hadoop-1-reserved.tgz";
private static final String HADOOP023_RESERVED_IMAGE =
"hadoop-0.23-reserved.tgz";
private static final String HADOOP2_RESERVED_IMAGE = "hadoop-2-reserved.tgz";
private static class ReferenceFileInfo {
String path;
long checksum;
}
static final Configuration upgradeConf;
static {
upgradeConf = new HdfsConfiguration();
upgradeConf.setInt(DFSConfigKeys.DFS_DATANODE_SCAN_PERIOD_HOURS_KEY, -1); // block scanning off
if (System.getProperty("test.build.data") == null) { // to allow test to be run outside of Maven
System.setProperty("test.build.data", "build/test/data");
}
}
public interface ClusterVerifier {
public void verifyClusterPostUpgrade(final MiniDFSCluster cluster) throws IOException;
}
final LinkedList<ReferenceFileInfo> refList = new LinkedList<ReferenceFileInfo>();
Iterator<ReferenceFileInfo> refIter;
boolean printChecksum = false;
void unpackStorage(String tarFileName, String referenceName)
throws IOException {
String tarFile = System.getProperty("test.cache.data", "build/test/cache")
+ "/" + tarFileName;
String dataDir = System.getProperty("test.build.data", "build/test/data");
File dfsDir = new File(dataDir, "dfs");
if ( dfsDir.exists() && !FileUtil.fullyDelete(dfsDir) ) {
throw new IOException("Could not delete dfs directory '" + dfsDir + "'");
}
LOG.info("Unpacking " + tarFile);
FileUtil.unTar(new File(tarFile), new File(dataDir));
//Now read the reference info
BufferedReader reader = new BufferedReader(new FileReader(
System.getProperty("test.cache.data", "build/test/cache")
+ "/" + referenceName));
String line;
while ( (line = reader.readLine()) != null ) {
line = line.trim();
if (line.length() <= 0 || line.startsWith("#")) {
continue;
}
String[] arr = line.split("\\s+");
if (arr.length < 1) {
continue;
}
if (arr[0].equals("printChecksums")) {
printChecksum = true;
break;
}
if (arr.length < 2) {
continue;
}
ReferenceFileInfo info = new ReferenceFileInfo();
info.path = arr[0];
info.checksum = Long.parseLong(arr[1]);
refList.add(info);
}
reader.close();
}
private void verifyChecksum(String path, long checksum) throws IOException {
if ( refIter == null ) {
refIter = refList.iterator();
}
if ( printChecksum ) {
LOG.info("CRC info for reference file : " + path + " \t " + checksum);
} else {
if ( !refIter.hasNext() ) {
throw new IOException("Checking checksum for " + path +
"Not enough elements in the refList");
}
ReferenceFileInfo info = refIter.next();
// The paths are expected to be listed in the same order
// as they are traversed here.
assertEquals(info.path, path);
assertEquals("Checking checksum for " + path, info.checksum, checksum);
}
}
/**
* Try to open a file for reading several times.
*
* If we fail because lease recovery hasn't completed, retry the open.
*/
private static FSInputStream dfsOpenFileWithRetries(DistributedFileSystem dfs,
String pathName) throws IOException {
IOException exc = null;
for (int tries = 0; tries < 10; tries++) {
try {
return dfs.dfs.open(pathName);
} catch (IOException e) {
exc = e;
}
if (!exc.getMessage().contains("Cannot obtain " +
"block length for LocatedBlock")) {
throw exc;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {}
}
throw exc;
}
private void verifyDir(DistributedFileSystem dfs, Path dir,
CRC32 overallChecksum) throws IOException {
FileStatus[] fileArr = dfs.listStatus(dir);
TreeMap<Path, Boolean> fileMap = new TreeMap<Path, Boolean>();
for(FileStatus file : fileArr) {
fileMap.put(file.getPath(), Boolean.valueOf(file.isDirectory()));
}
for(Iterator<Path> it = fileMap.keySet().iterator(); it.hasNext();) {
Path path = it.next();
boolean isDir = fileMap.get(path);
String pathName = path.toUri().getPath();
overallChecksum.update(pathName.getBytes());
if ( isDir ) {
verifyDir(dfs, path, overallChecksum);
} else {
// this is not a directory. Checksum the file data.
CRC32 fileCRC = new CRC32();
FSInputStream in = dfsOpenFileWithRetries(dfs, pathName);
byte[] buf = new byte[4096];
int nRead = 0;
while ( (nRead = in.read(buf, 0, buf.length)) > 0 ) {
fileCRC.update(buf, 0, nRead);
}
verifyChecksum(pathName, fileCRC.getValue());
}
}
}
private void verifyFileSystem(DistributedFileSystem dfs) throws IOException {
CRC32 overallChecksum = new CRC32();
verifyDir(dfs, new Path("/"), overallChecksum);
verifyChecksum("overallCRC", overallChecksum.getValue());
if ( printChecksum ) {
throw new IOException("Checksums are written to log as requested. " +
"Throwing this exception to force an error " +
"for this test.");
}
}
/**
* Test that sets up a fake image from Hadoop 0.3.0 and tries to start a
* NN, verifying that the correct error message is thrown.
*/
@Test
public void testFailOnPreUpgradeImage() throws IOException {
Configuration conf = new HdfsConfiguration();
File namenodeStorage = new File(TEST_ROOT_DIR, "nnimage-0.3.0");
conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, namenodeStorage.toString());
// Set up a fake NN storage that looks like an ancient Hadoop dir circa 0.3.0
FileUtil.fullyDelete(namenodeStorage);
assertTrue("Make " + namenodeStorage, namenodeStorage.mkdirs());
File imageDir = new File(namenodeStorage, "image");
assertTrue("Make " + imageDir, imageDir.mkdirs());
// Hex dump of a formatted image from Hadoop 0.3.0
File imageFile = new File(imageDir, "fsimage");
byte[] imageBytes = StringUtils.hexStringToByte(
"fffffffee17c0d2700000000");
FileOutputStream fos = new FileOutputStream(imageFile);
try {
fos.write(imageBytes);
} finally {
fos.close();
}
// Now try to start an NN from it
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0)
.format(false)
.manageDataDfsDirs(false)
.manageNameDfsDirs(false)
.startupOption(StartupOption.REGULAR)
.build();
fail("Was able to start NN from 0.3.0 image");
} catch (IOException ioe) {
if (!ioe.toString().contains("Old layout version is 'too old'")) {
throw ioe;
}
} finally {
// We expect startup to fail, but just in case it didn't, shutdown now.
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test upgrade from 0.22 image
*/
@Test
public void testUpgradeFromRel22Image() throws IOException {
unpackStorage(HADOOP22_IMAGE, HADOOP_DFS_DIR_TXT);
upgradeAndVerify(new MiniDFSCluster.Builder(upgradeConf).
numDataNodes(4), null);
}
/**
* Test upgrade from 0.22 image with corrupt md5, make sure it
* fails to upgrade
*/
@Test
public void testUpgradeFromCorruptRel22Image() throws IOException {
unpackStorage(HADOOP22_IMAGE, HADOOP_DFS_DIR_TXT);
// Overwrite the md5 stored in the VERSION files
File[] nnDirs = MiniDFSCluster.getNameNodeDirectory(MiniDFSCluster.getBaseDirectory(), 0, 0);
FSImageTestUtil.corruptVersionFile(
new File(nnDirs[0], "current/VERSION"),
"imageMD5Digest", "22222222222222222222222222222222");
FSImageTestUtil.corruptVersionFile(
new File(nnDirs[1], "current/VERSION"),
"imageMD5Digest", "22222222222222222222222222222222");
// Attach our own log appender so we can verify output
final LogVerificationAppender appender = new LogVerificationAppender();
final Logger logger = Logger.getRootLogger();
logger.addAppender(appender);
// Upgrade should now fail
try {
upgradeAndVerify(new MiniDFSCluster.Builder(upgradeConf).
numDataNodes(4), null);
fail("Upgrade did not fail with bad MD5");
} catch (IOException ioe) {
String msg = StringUtils.stringifyException(ioe);
if (!msg.contains("Failed to load an FSImage file")) {
throw ioe;
}
int md5failures = appender.countExceptionsWithMessage(
" is corrupt with MD5 checksum of ");
assertEquals("Upgrade did not fail with bad MD5", 1, md5failures);
}
}
/**
* Test upgrade from a branch-1.2 image with reserved paths
*/
@Test
public void testUpgradeFromRel1ReservedImage() throws Exception {
unpackStorage(HADOOP1_RESERVED_IMAGE, HADOOP_DFS_DIR_TXT);
MiniDFSCluster cluster = null;
// Try it once without setting the upgrade flag to ensure it fails
final Configuration conf = new Configuration();
// Try it again with a custom rename string
try {
FSImageFormat.setRenameReservedPairs(
".snapshot=.user-snapshot," +
".reserved=.my-reserved");
cluster =
new MiniDFSCluster.Builder(conf)
.format(false)
.startupOption(StartupOption.UPGRADE)
.numDataNodes(0).build();
DistributedFileSystem dfs = cluster.getFileSystem();
// Make sure the paths were renamed as expected
// Also check that paths are present after a restart, checks that the
// upgraded fsimage has the same state.
final String[] expected = new String[] {
"/.my-reserved",
"/.user-snapshot",
"/.user-snapshot/.user-snapshot",
"/.user-snapshot/open",
"/dir1",
"/dir1/.user-snapshot",
"/dir2",
"/dir2/.user-snapshot",
"/user",
"/user/andrew",
"/user/andrew/.user-snapshot",
};
for (int i=0; i<2; i++) {
// Restart the second time through this loop
if (i==1) {
cluster.finalizeCluster(conf);
cluster.restartNameNode(true);
}
ArrayList<Path> toList = new ArrayList<Path>();
toList.add(new Path("/"));
ArrayList<String> found = new ArrayList<String>();
while (!toList.isEmpty()) {
Path p = toList.remove(0);
FileStatus[] statuses = dfs.listStatus(p);
for (FileStatus status: statuses) {
final String path = status.getPath().toUri().getPath();
System.out.println("Found path " + path);
found.add(path);
if (status.isDirectory()) {
toList.add(status.getPath());
}
}
}
for (String s: expected) {
assertTrue("Did not find expected path " + s, found.contains(s));
}
assertEquals("Found an unexpected path while listing filesystem",
found.size(), expected.length);
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test upgrade from a 0.23.11 image with reserved paths
*/
@Test
public void testUpgradeFromRel023ReservedImage() throws Exception {
unpackStorage(HADOOP023_RESERVED_IMAGE, HADOOP_DFS_DIR_TXT);
MiniDFSCluster cluster = null;
// Try it once without setting the upgrade flag to ensure it fails
final Configuration conf = new Configuration();
// Try it again with a custom rename string
try {
FSImageFormat.setRenameReservedPairs(
".snapshot=.user-snapshot," +
".reserved=.my-reserved");
cluster =
new MiniDFSCluster.Builder(conf)
.format(false)
.startupOption(StartupOption.UPGRADE)
.numDataNodes(0).build();
DistributedFileSystem dfs = cluster.getFileSystem();
// Make sure the paths were renamed as expected
// Also check that paths are present after a restart, checks that the
// upgraded fsimage has the same state.
final String[] expected = new String[] {
"/.user-snapshot",
"/dir1",
"/dir1/.user-snapshot",
"/dir2",
"/dir2/.user-snapshot"
};
for (int i=0; i<2; i++) {
// Restart the second time through this loop
if (i==1) {
cluster.finalizeCluster(conf);
cluster.restartNameNode(true);
}
ArrayList<Path> toList = new ArrayList<Path>();
toList.add(new Path("/"));
ArrayList<String> found = new ArrayList<String>();
while (!toList.isEmpty()) {
Path p = toList.remove(0);
FileStatus[] statuses = dfs.listStatus(p);
for (FileStatus status: statuses) {
final String path = status.getPath().toUri().getPath();
System.out.println("Found path " + path);
found.add(path);
if (status.isDirectory()) {
toList.add(status.getPath());
}
}
}
for (String s: expected) {
assertTrue("Did not find expected path " + s, found.contains(s));
}
assertEquals("Found an unexpected path while listing filesystem",
found.size(), expected.length);
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test upgrade from 2.0 image with a variety of .snapshot and .reserved
* paths to test renaming on upgrade
*/
@Test
public void testUpgradeFromRel2ReservedImage() throws Exception {
unpackStorage(HADOOP2_RESERVED_IMAGE, HADOOP_DFS_DIR_TXT);
MiniDFSCluster cluster = null;
// Try it once without setting the upgrade flag to ensure it fails
final Configuration conf = new Configuration();
try {
cluster =
new MiniDFSCluster.Builder(conf)
.format(false)
.startupOption(StartupOption.UPGRADE)
.numDataNodes(0).build();
} catch (IllegalArgumentException e) {
GenericTestUtils.assertExceptionContains(
"reserved path component in this version",
e);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
// Try it again with a custom rename string
try {
FSImageFormat.setRenameReservedPairs(
".snapshot=.user-snapshot," +
".reserved=.my-reserved");
cluster =
new MiniDFSCluster.Builder(conf)
.format(false)
.startupOption(StartupOption.UPGRADE)
.numDataNodes(0).build();
DistributedFileSystem dfs = cluster.getFileSystem();
// Make sure the paths were renamed as expected
// Also check that paths are present after a restart, checks that the
// upgraded fsimage has the same state.
final String[] expected = new String[] {
"/edits",
"/edits/.reserved",
"/edits/.user-snapshot",
"/edits/.user-snapshot/editsdir",
"/edits/.user-snapshot/editsdir/editscontents",
"/edits/.user-snapshot/editsdir/editsdir2",
"/image",
"/image/.reserved",
"/image/.user-snapshot",
"/image/.user-snapshot/imagedir",
"/image/.user-snapshot/imagedir/imagecontents",
"/image/.user-snapshot/imagedir/imagedir2",
"/.my-reserved",
"/.my-reserved/edits-touch",
"/.my-reserved/image-touch"
};
for (int i=0; i<2; i++) {
// Restart the second time through this loop
if (i==1) {
cluster.finalizeCluster(conf);
cluster.restartNameNode(true);
}
ArrayList<Path> toList = new ArrayList<Path>();
toList.add(new Path("/"));
ArrayList<String> found = new ArrayList<String>();
while (!toList.isEmpty()) {
Path p = toList.remove(0);
FileStatus[] statuses = dfs.listStatus(p);
for (FileStatus status: statuses) {
final String path = status.getPath().toUri().getPath();
System.out.println("Found path " + path);
found.add(path);
if (status.isDirectory()) {
toList.add(status.getPath());
}
}
}
for (String s: expected) {
assertTrue("Did not find expected path " + s, found.contains(s));
}
assertEquals("Found an unexpected path while listing filesystem",
found.size(), expected.length);
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
static void recoverAllLeases(DFSClient dfs,
Path path) throws IOException {
String pathStr = path.toString();
HdfsFileStatus status = dfs.getFileInfo(pathStr);
if (!status.isDir()) {
dfs.recoverLease(pathStr);
return;
}
byte prev[] = HdfsFileStatus.EMPTY_NAME;
DirectoryListing dirList;
do {
dirList = dfs.listPaths(pathStr, prev);
HdfsFileStatus files[] = dirList.getPartialListing();
for (HdfsFileStatus f : files) {
recoverAllLeases(dfs, f.getFullPath(path));
}
prev = dirList.getLastName();
} while (dirList.hasMore());
}
void upgradeAndVerify(MiniDFSCluster.Builder bld, ClusterVerifier verifier)
throws IOException {
MiniDFSCluster cluster = null;
try {
bld.format(false).startupOption(StartupOption.UPGRADE)
.clusterId("testClusterId");
cluster = bld.build();
cluster.waitActive();
DistributedFileSystem dfs = cluster.getFileSystem();
DFSClient dfsClient = dfs.dfs;
//Safemode will be off only after upgrade is complete. Wait for it.
while ( dfsClient.setSafeMode(HdfsConstants.SafeModeAction.SAFEMODE_GET) ) {
LOG.info("Waiting for SafeMode to be OFF.");
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {}
}
recoverAllLeases(dfsClient, new Path("/"));
verifyFileSystem(dfs);
if (verifier != null) {
verifier.verifyClusterPostUpgrade(cluster);
}
} finally {
if (cluster != null) { cluster.shutdown(); }
}
}
/**
* Test upgrade from a 1.x image with some blocksBeingWritten
*/
@Test
public void testUpgradeFromRel1BBWImage() throws IOException {
unpackStorage(HADOOP1_BBW_IMAGE, HADOOP_DFS_DIR_TXT);
Configuration conf = new Configuration(upgradeConf);
conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY,
System.getProperty("test.build.data") + File.separator +
"dfs" + File.separator +
"data" + File.separator +
"data1");
upgradeAndVerify(new MiniDFSCluster.Builder(conf).
numDataNodes(1).enableManagedDfsDirsRedundancy(false).
manageDataDfsDirs(false), null);
}
}
| likaiwalkman/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgradeFromImage.java | Java | apache-2.0 | 22,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.