index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/CassandraTableResourceFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider;
//import org.mortbay.log.Log;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.netflix.astyanax.Keyspace;
import com.netflix.paas.cassandra.keys.ClusterKey;
import com.netflix.paas.cassandra.keys.KeyspaceKey;
import com.netflix.paas.cassandra.resources.AstyanaxThriftDataTableResource;
import com.netflix.paas.entity.TableEntity;
import com.netflix.paas.exceptions.NotFoundException;
import com.netflix.paas.provider.TableDataResourceFactory;
import com.netflix.paas.resources.TableDataResource;
public class CassandraTableResourceFactory implements TableDataResourceFactory {
private final KeyspaceClientProvider clientProvider;
@Inject
public CassandraTableResourceFactory(KeyspaceClientProvider clientProvider) {
this.clientProvider = clientProvider;
}
@Override
public TableDataResource getTableDataResource(TableEntity table) throws NotFoundException {
//Log.info(table.toString());
String clusterName = table.getOption("cassandra.cluster");
String keyspaceName = table.getOption("cassandra.keyspace");
String columnFamilyName = table.getOption("cassandra.columnfamily");
String discoveryType = table.getOption("discovery");
if (discoveryType == null)
discoveryType = "eureka";
Preconditions.checkNotNull(clusterName, "Must specify cluster name for table " + table.getTableName());
Preconditions.checkNotNull(keyspaceName, "Must specify keyspace name for table " + table.getTableName());
Preconditions.checkNotNull(columnFamilyName, "Must specify column family name for table " + table.getTableName());
Preconditions.checkNotNull(discoveryType, "Must specify discovery type for table " + table.getTableName());
Keyspace keyspace = clientProvider.acquireKeyspace(new KeyspaceKey(new ClusterKey(clusterName, discoveryType), keyspaceName));
return new AstyanaxThriftDataTableResource(keyspace, columnFamilyName);
}
}
| 3,300 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/AstyanaxConfigurationProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider;
import com.netflix.astyanax.AstyanaxConfiguration;
public interface AstyanaxConfigurationProvider {
public AstyanaxConfiguration get(String name);
}
| 3,301 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/AnnotatedAstyanaxConfiguration.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import java.util.concurrent.ExecutorService;
import com.netflix.astyanax.AstyanaxConfiguration;
import com.netflix.astyanax.Clock;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.retry.RunOnce;
import com.netflix.governator.annotations.Configuration;
public class AnnotatedAstyanaxConfiguration implements AstyanaxConfiguration {
@Configuration("${prefix}.${name}.retryPolicy")
private RetryPolicy retryPolicy = RunOnce.get();
@Configuration("${prefix}.${name}.defaultReadConsistencyLevel")
private ConsistencyLevel defaultReadConsistencyLevel = ConsistencyLevel.CL_ONE;
@Configuration("${prefix}.${name}.defaultWriteConsistencyLevel")
private ConsistencyLevel defaultWriteConsistencyLevel = ConsistencyLevel.CL_ONE;
@Configuration("${prefix}.${name}.clock")
private String clockName = null;
@Configuration("${prefix}.${name}.discoveryDelayInSeconds")
private int discoveryDelayInSeconds;
@Configuration("${prefix}.${name}.discoveryType")
private NodeDiscoveryType discoveryType;
@Configuration("${prefix}.${name}.connectionPoolType")
private ConnectionPoolType getConnectionPoolType;
@Configuration("${prefix}.${name}.cqlVersion")
private String cqlVersion;
private Clock clock;
void initialize() {
}
void cleanup() {
}
@Override
public RetryPolicy getRetryPolicy() {
return retryPolicy;
}
@Override
public ConsistencyLevel getDefaultReadConsistencyLevel() {
return this.defaultReadConsistencyLevel;
}
@Override
public ConsistencyLevel getDefaultWriteConsistencyLevel() {
return this.defaultWriteConsistencyLevel;
}
@Override
public Clock getClock() {
return this.clock;
}
@Override
public ExecutorService getAsyncExecutor() {
return null;
}
@Override
public int getDiscoveryDelayInSeconds() {
// TODO Auto-generated method stub
return 0;
}
@Override
public NodeDiscoveryType getDiscoveryType() {
// TODO Auto-generated method stub
return null;
}
@Override
public ConnectionPoolType getConnectionPoolType() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getCqlVersion() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getTargetCassandraVersion() {
// TODO Auto-generated method stub
return null;
}
@Override
public Partitioner getPartitioner(String partitionerName) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| 3,302 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxConnectionPoolConfigurationProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider;
public class DefaultAstyanaxConnectionPoolConfigurationProvider implements AstyanaxConnectionPoolConfigurationProvider {
@Override
public ConnectionPoolConfiguration get(String name) {
return new ConnectionPoolConfigurationImpl(name);
}
}
| 3,303 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/LocalHostSupplierProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import java.util.List;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.paas.cassandra.provider.HostSupplierProvider;
public class LocalHostSupplierProvider implements HostSupplierProvider {
private final List<Host> localhost;
public LocalHostSupplierProvider() {
localhost = Lists.newArrayList(new Host("localhost", 9160));
}
@Override
public Supplier<List<Host>> getSupplier(String clusterName) {
return Suppliers.ofInstance(localhost);
}
}
| 3,304 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxConfigurationProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import com.netflix.astyanax.AstyanaxConfiguration;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider;
public class DefaultAstyanaxConfigurationProvider implements AstyanaxConfigurationProvider {
@Override
public AstyanaxConfiguration get(String name) {
return new AstyanaxConfigurationImpl()
.setDiscoveryType(NodeDiscoveryType.NONE)
.setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN)
.setDiscoveryDelayInSeconds(60000)
.setCqlVersion("3.0.0");
}
}
| 3,305 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxConnectionPoolMonitorProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.impl.Slf4jConnectionPoolMonitorImpl;
import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider;
public class DefaultAstyanaxConnectionPoolMonitorProvider implements AstyanaxConnectionPoolMonitorProvider {
@Override
public ConnectionPoolMonitor get(String name) {
return new Slf4jConnectionPoolMonitorImpl();
}
}
| 3,306 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxClusterClientProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.configuration.AbstractConfiguration;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Cluster;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
import com.netflix.paas.cassandra.keys.ClusterKey;
import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider;
import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider;
import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider;
import com.netflix.paas.cassandra.provider.ClusterClientProvider;
import com.netflix.paas.cassandra.provider.HostSupplierProvider;
public class DefaultAstyanaxClusterClientProvider implements ClusterClientProvider {
/**
* Track cluster references
*
* @author elandau
*
*/
public static class ClusterContextHolder {
private AstyanaxContext<Cluster> context;
private AtomicLong refCount = new AtomicLong(0);
public ClusterContextHolder(AstyanaxContext<Cluster> context) {
this.context = context;
}
public Cluster getKeyspace() {
return context.getClient();
}
public void start() {
context.start();
}
public void shutdown() {
context.shutdown();
}
public long addRef() {
return refCount.incrementAndGet();
}
public long releaseRef() {
return refCount.decrementAndGet();
}
}
private final Map<String, ClusterContextHolder> contextMap = Maps.newHashMap();
private final AstyanaxConfigurationProvider configurationProvider;
private final AstyanaxConnectionPoolConfigurationProvider cpProvider;
private final AstyanaxConnectionPoolMonitorProvider monitorProvider;
private final Map<String, HostSupplierProvider> hostSupplierProviders;
private final AbstractConfiguration configuration;
@Inject
public DefaultAstyanaxClusterClientProvider(
AbstractConfiguration configuration,
Map<String, HostSupplierProvider> hostSupplierProviders,
AstyanaxConfigurationProvider configurationProvider,
AstyanaxConnectionPoolConfigurationProvider cpProvider,
AstyanaxConnectionPoolMonitorProvider monitorProvider) {
this.configurationProvider = configurationProvider;
this.cpProvider = cpProvider;
this.monitorProvider = monitorProvider;
this.hostSupplierProviders = hostSupplierProviders;
this.configuration = configuration;
}
@Override
public synchronized Cluster acquireCluster(ClusterKey clusterKey) {
String clusterName = clusterKey.getClusterName().toLowerCase();
Preconditions.checkNotNull(clusterName, "Invalid cluster name 'null'");
ClusterContextHolder holder = contextMap.get(clusterName);
if (holder == null) {
HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(clusterKey.getDiscoveryType());
Preconditions.checkNotNull(hostSupplierProvider, String.format("Unknown host supplier provider '%s' for cluster '%s'", clusterKey.getDiscoveryType(), clusterName));
AstyanaxContext<Cluster> context = new AstyanaxContext.Builder()
.forCluster(clusterName)
.withAstyanaxConfiguration(configurationProvider.get(clusterName))
.withConnectionPoolConfiguration(cpProvider.get(clusterName))
.withConnectionPoolMonitor(monitorProvider.get(clusterName))
.withHostSupplier(hostSupplierProvider.getSupplier(clusterName))
.buildCluster(ThriftFamilyFactory.getInstance());
holder = new ClusterContextHolder(context);
holder.start();
}
holder.addRef();
return holder.getKeyspace();
}
@Override
public synchronized void releaseCluster(ClusterKey clusterKey) {
String clusterName = clusterKey.getClusterName().toLowerCase();
ClusterContextHolder holder = contextMap.get(clusterName);
if (holder.releaseRef() == 0) {
contextMap.remove(clusterName);
holder.shutdown();
}
}
}
| 3,307 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultKeyspaceClientProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.provider.impl;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.configuration.AbstractConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
import com.netflix.paas.cassandra.keys.KeyspaceKey;
import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider;
import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider;
import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider;
import com.netflix.paas.cassandra.provider.HostSupplierProvider;
import com.netflix.paas.cassandra.provider.KeyspaceClientProvider;
public class DefaultKeyspaceClientProvider implements KeyspaceClientProvider {
private static final Logger LOG = LoggerFactory.getLogger(DefaultKeyspaceClientProvider.class);
private static final String DISCOVERY_TYPE_FORMAT = "com.netflix.paas.schema.%s.discovery";
private static final String CLUSTER_NAME_FORMAT = "com.netflix.paas.schema.%s.cluster";
private static final String KEYSPACE_NAME__FORMAT = "com.netflix.paas.schema.%s.keyspace";
ImmutableMap<String, Object> defaultKsOptions = ImmutableMap.<String, Object>builder()
.put("strategy_options", ImmutableMap.<String, Object>builder()
.put("replication_factor", "1")
.build())
.put("strategy_class", "SimpleStrategy")
.build();
public static class KeyspaceContextHolder {
private AstyanaxContext<Keyspace> context;
private AtomicLong refCount = new AtomicLong(0);
public KeyspaceContextHolder(AstyanaxContext<Keyspace> context) {
this.context = context;
}
public Keyspace getKeyspace() {
return context.getClient();
}
public void start() {
context.start();
}
public void shutdown() {
context.shutdown();
}
public long addRef() {
return refCount.incrementAndGet();
}
public long releaseRef() {
return refCount.decrementAndGet();
}
}
private final Map<String, KeyspaceContextHolder> contextMap = Maps.newHashMap();
private final AstyanaxConfigurationProvider configurationProvider;
private final AstyanaxConnectionPoolConfigurationProvider cpProvider;
private final AstyanaxConnectionPoolMonitorProvider monitorProvider;
private final Map<String, HostSupplierProvider> hostSupplierProviders;
private final AbstractConfiguration configuration;
@Inject
public DefaultKeyspaceClientProvider(
AbstractConfiguration configuration,
Map<String, HostSupplierProvider> hostSupplierProviders,
AstyanaxConfigurationProvider configurationProvider,
AstyanaxConnectionPoolConfigurationProvider cpProvider,
AstyanaxConnectionPoolMonitorProvider monitorProvider) {
this.configurationProvider = configurationProvider;
this.cpProvider = cpProvider;
this.monitorProvider = monitorProvider;
this.hostSupplierProviders = hostSupplierProviders;
this.configuration = configuration;
}
@Override
public synchronized Keyspace acquireKeyspace(String schemaName) {
schemaName = schemaName.toLowerCase();
Preconditions.checkNotNull(schemaName, "Invalid schema name 'null'");
KeyspaceContextHolder holder = contextMap.get(schemaName);
if (holder == null) {
LOG.info("Creating schema for '{}'", new Object[]{schemaName});
String clusterName = configuration.getString(String.format(CLUSTER_NAME_FORMAT, schemaName));
String keyspaceName = configuration.getString(String.format(KEYSPACE_NAME__FORMAT, schemaName));
String discoveryType = configuration.getString(String.format(DISCOVERY_TYPE_FORMAT, schemaName));
if (clusterName==null || clusterName.equals("")) clusterName = configuration.getString(String.format(CLUSTER_NAME_FORMAT, "configuration"));
if (keyspaceName == null || keyspaceName.equals("")) keyspaceName = schemaName;
if (discoveryType==null || discoveryType.equals("")) discoveryType = configuration.getString(String.format(DISCOVERY_TYPE_FORMAT, "configuration"));
Preconditions.checkNotNull(clusterName, "Missing cluster name for schema " + schemaName + " " + String.format(CLUSTER_NAME_FORMAT,schemaName));
Preconditions.checkNotNull(keyspaceName, "Missing cluster name for schema " + schemaName + " " + String.format(KEYSPACE_NAME__FORMAT,schemaName));
Preconditions.checkNotNull(discoveryType, "Missing cluster name for schema " + schemaName + " " + String.format(DISCOVERY_TYPE_FORMAT,schemaName));
HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(discoveryType);
Preconditions.checkNotNull(hostSupplierProvider,
String.format("Unknown host supplier provider '%s' for schema '%s'", discoveryType, schemaName));
AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
.forCluster(clusterName)
.forKeyspace(keyspaceName)
.withAstyanaxConfiguration(configurationProvider.get(schemaName))
.withConnectionPoolConfiguration(cpProvider.get(schemaName))
.withConnectionPoolMonitor(monitorProvider.get(schemaName))
.withHostSupplier(hostSupplierProvider.getSupplier(clusterName))
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
try {
context.getClient().createKeyspace(defaultKsOptions);
} catch (ConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
holder = new KeyspaceContextHolder(context);
contextMap.put(schemaName, holder);
holder.start();
}
holder.addRef();
return holder.getKeyspace();
}
@Override
public synchronized void releaseKeyspace(String schemaName) {
KeyspaceContextHolder holder = contextMap.get(schemaName);
if (holder.releaseRef() == 0) {
contextMap.remove(schemaName);
holder.shutdown();
}
}
@Override
public Keyspace acquireKeyspace(KeyspaceKey key) {
String schemaName = key.getSchemaName().toLowerCase();
Preconditions.checkNotNull(schemaName, "Invalid schema name 'null'");
KeyspaceContextHolder holder = contextMap.get(schemaName);
if (holder == null) {
Preconditions.checkNotNull(key.getClusterName(), "Missing cluster name for schema " + schemaName);
Preconditions.checkNotNull(key.getKeyspaceName(), "Missing cluster name for schema " + schemaName);
Preconditions.checkNotNull(key.getDiscoveryType(), "Missing cluster name for schema " + schemaName);
HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(key.getDiscoveryType());
Preconditions.checkNotNull(hostSupplierProvider, "Unknown host supplier provider " + key.getDiscoveryType());
AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
.forCluster(key.getClusterName())
.forKeyspace(key.getKeyspaceName())
.withAstyanaxConfiguration(configurationProvider.get(schemaName))
.withConnectionPoolConfiguration(cpProvider.get(schemaName))
.withConnectionPoolMonitor(monitorProvider.get(schemaName))
.withHostSupplier(hostSupplierProvider.getSupplier(key.getClusterName()))
.buildKeyspace(ThriftFamilyFactory.getInstance());
holder = new KeyspaceContextHolder(context);
contextMap.put(schemaName, holder);
holder.start();
}
holder.addRef();
return holder.getKeyspace();
}
}
| 3,308 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/keys/ColumnFamilyKey.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.keys;
import org.apache.commons.lang.StringUtils;
public class ColumnFamilyKey {
private final KeyspaceKey keyspaceKey;
private final String columnFamilyName;
public ColumnFamilyKey(KeyspaceKey keyspaceKey, String columnFamilyName) {
super();
this.keyspaceKey = keyspaceKey;
this.columnFamilyName = columnFamilyName;
}
public ColumnFamilyKey(ClusterKey clusterKey, String keyspaceName, String columnFamilyName) {
this.keyspaceKey = new KeyspaceKey(clusterKey, keyspaceName);
this.columnFamilyName = columnFamilyName;
}
public KeyspaceKey getKeyspaceKey() {
return keyspaceKey;
}
public String getColumnFamilyName() {
return columnFamilyName;
}
public String getCanonicalName() {
return StringUtils.join(new String[]{keyspaceKey.getCanonicalName(), columnFamilyName}, ".");
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((columnFamilyName == null) ? 0 : columnFamilyName.hashCode());
result = prime * result
+ ((keyspaceKey == null) ? 0 : keyspaceKey.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ColumnFamilyKey other = (ColumnFamilyKey) obj;
if (columnFamilyName == null) {
if (other.columnFamilyName != null)
return false;
} else if (!columnFamilyName.equals(other.columnFamilyName))
return false;
if (keyspaceKey == null) {
if (other.keyspaceKey != null)
return false;
} else if (!keyspaceKey.equals(other.keyspaceKey))
return false;
return true;
}
}
| 3,309 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/keys/ClusterKey.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.keys;
import org.apache.commons.lang.StringUtils;
public class ClusterKey {
private final String clusterName;
private final String discoveryType;
public ClusterKey(String clusterName, String discoveryType) {
this.clusterName = clusterName;
this.discoveryType = discoveryType;
}
public String getDiscoveryType() {
return discoveryType;
}
public String getClusterName() {
return this.clusterName;
}
public String getCanonicalName() {
return StringUtils.join(new String[]{this.discoveryType, this.clusterName}, ".");
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((clusterName == null) ? 0 : clusterName.hashCode());
result = prime * result
+ ((discoveryType == null) ? 0 : discoveryType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClusterKey other = (ClusterKey) obj;
if (clusterName == null) {
if (other.clusterName != null)
return false;
} else if (!clusterName.equals(other.clusterName))
return false;
if (discoveryType == null) {
if (other.discoveryType != null)
return false;
} else if (!discoveryType.equals(other.discoveryType))
return false;
return true;
}
}
| 3,310 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/keys/KeyspaceKey.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.keys;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Preconditions;
/**
* Global unique keyspace identifier
* @author elandau
*
*/
public class KeyspaceKey {
private final ClusterKey clusterKey;
private final String keyspaceName;
private final String schemaName;
public KeyspaceKey(String schemaName) {
String parts[] = StringUtils.split(schemaName, ".");
Preconditions.checkState(parts.length == 2, String.format("Schema name must have format <cluster>.<keyspace> ('%s')", schemaName));
this.clusterKey = new ClusterKey(parts[0], null); // TODO
this.keyspaceName = parts[1];
this.schemaName = schemaName;
}
public KeyspaceKey(ClusterKey clusterKey, String keyspaceName) {
this.clusterKey = clusterKey;
this.keyspaceName = keyspaceName;
this.schemaName = StringUtils.join(new String[]{clusterKey.getClusterName(), keyspaceName}, ".");
}
public ClusterKey getClusterKey() {
return clusterKey;
}
public String getClusterName() {
return clusterKey.getClusterName();
}
public String getKeyspaceName() {
return this.keyspaceName;
}
public String getDiscoveryType() {
return this.clusterKey.getDiscoveryType();
}
public String getSchemaName() {
return this.schemaName;
}
public String getCanonicalName() {
return StringUtils.join(new String[]{this.clusterKey.getCanonicalName(), getKeyspaceName()}, ".");
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((clusterKey == null) ? 0 : clusterKey.hashCode());
result = prime * result
+ ((keyspaceName == null) ? 0 : keyspaceName.hashCode());
result = prime * result
+ ((schemaName == null) ? 0 : schemaName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
KeyspaceKey other = (KeyspaceKey) obj;
if (clusterKey == null) {
if (other.clusterKey != null)
return false;
} else if (!clusterKey.equals(other.clusterKey))
return false;
if (keyspaceName == null) {
if (other.keyspaceName != null)
return false;
} else if (!keyspaceName.equals(other.keyspaceName))
return false;
if (schemaName == null) {
if (other.schemaName != null)
return false;
} else if (!schemaName.equals(other.schemaName))
return false;
return true;
}
}
| 3,311 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/service/ClusterMetaService.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.service;
import com.google.common.eventbus.Subscribe;
import com.netflix.paas.cassandra.events.ClusterUpdateEvent;
import com.netflix.paas.cassandra.events.ColumnFamilyDeleteEvent;
import com.netflix.paas.cassandra.events.ColumnFamilyUpdateEvent;
import com.netflix.paas.cassandra.events.KeyspaceDeleteEvent;
import com.netflix.paas.cassandra.events.KeyspaceUpdateEvent;
public class ClusterMetaService {
public ClusterMetaService() {
}
@Subscribe
public void handleClusterUpdateEvent(ClusterUpdateEvent event) {
}
@Subscribe
public void handleKeyspaceUpdateEvent(KeyspaceUpdateEvent event) {
}
@Subscribe
public void handleKeyspaceDeleteEvent(KeyspaceDeleteEvent event) {
}
@Subscribe
public void handleColumnFamilyUpdateEvent(ColumnFamilyUpdateEvent event) {
}
@Subscribe
public void handleColumnFamilyDeleteEvent(ColumnFamilyDeleteEvent event) {
}
}
| 3,312 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/ColumnFamilyDeleteEvent.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.events;
import com.netflix.paas.cassandra.keys.ColumnFamilyKey;
public class ColumnFamilyDeleteEvent {
private final ColumnFamilyKey columnFamilyKey;
public ColumnFamilyDeleteEvent(ColumnFamilyKey columnFamilyKey) {
super();
this.columnFamilyKey = columnFamilyKey;
}
public ColumnFamilyKey getColumnFamilyKey() {
return columnFamilyKey;
}
}
| 3,313 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/KeyspaceDeleteEvent.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.events;
import com.netflix.paas.cassandra.keys.KeyspaceKey;
public class KeyspaceDeleteEvent {
private final KeyspaceKey keyspaceKey;
public KeyspaceDeleteEvent(KeyspaceKey keyspaceKey) {
super();
this.keyspaceKey = keyspaceKey;
}
public KeyspaceKey getKeyspaceKey() {
return keyspaceKey;
}
}
| 3,314 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/ColumnFamilyUpdateEvent.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.events;
import com.netflix.paas.cassandra.keys.ColumnFamilyKey;
public class ColumnFamilyUpdateEvent {
private final ColumnFamilyKey columnFamilyKey;
public ColumnFamilyUpdateEvent(ColumnFamilyKey columnFamilyKey) {
super();
this.columnFamilyKey = columnFamilyKey;
}
public ColumnFamilyKey getColumnFamilyKey() {
return columnFamilyKey;
}
}
| 3,315 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/ClusterUpdateEvent.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.events;
import com.netflix.paas.cassandra.keys.ClusterKey;
public class ClusterUpdateEvent {
private final ClusterKey clusterKey;
public ClusterUpdateEvent(ClusterKey clusterKey) {
super();
this.clusterKey = clusterKey;
}
public ClusterKey getClusterKey() {
return clusterKey;
}
}
| 3,316 |
0 |
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
|
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/KeyspaceUpdateEvent.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.cassandra.events;
import com.netflix.paas.cassandra.keys.KeyspaceKey;
public class KeyspaceUpdateEvent {
private final KeyspaceKey keyspaceKey;
public KeyspaceUpdateEvent(KeyspaceKey keyspaceKey) {
super();
this.keyspaceKey = keyspaceKey;
}
public KeyspaceKey getKeyspaceKey() {
return keyspaceKey;
}
}
| 3,317 |
0 |
Create_ds/staash/staash-core/src/test/java/com/netflix
|
Create_ds/staash/staash-core/src/test/java/com/netflix/paas/TrieTest.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class TrieTest {
public static interface TrieNodeVisitor {
void visit(TrieNode node);
}
public static interface TrieNode {
public TrieNode getOrCreateChild(Character c);
public TrieNode getChild(Character c);
public Character getCharacter();
public void setIsWord(boolean isWord);
public boolean isWord();
public void accept(TrieNodeVisitor visitor);
}
public static class HashMapTrieNode implements TrieNode {
private final ConcurrentMap<Character, TrieNode> children = Maps.newConcurrentMap();
private final Character character;
private volatile boolean isWord = false;
public HashMapTrieNode(Character ch) {
this.character = ch;
}
public TrieNode getChild(Character c) {
return children.get(c);
}
public TrieNode getOrCreateChild(Character c) {
TrieNode node = children.get(c);
if (node == null) {
TrieNode newNode = new HashMapTrieNode(c);
System.out.println("Create child : " + c);
node = children.putIfAbsent(c, newNode);
if (node == null)
return newNode;
}
return node;
}
public void setIsWord(boolean isWord) {
this.isWord = isWord;
}
public boolean isWord() {
return isWord;
}
@Override
public Character getCharacter() {
return this.character;
}
public void accept(TrieNodeVisitor visitor) {
List<TrieNode> nodes = Lists.newArrayList(children.values());
Collections.sort(nodes, new Comparator<TrieNode>() {
@Override
public int compare(TrieNode arg0, TrieNode arg1) {
return arg0.getCharacter().compareTo(arg1.getCharacter());
}
});
for (TrieNode node : nodes) {
visitor.visit(node);
}
}
}
public static class AtomicTrieNode implements TrieNode {
private final AtomicReference<Map<Character, TrieNode>> children = new AtomicReference<Map<Character, TrieNode>>();
private final Character character;
private volatile boolean isWord = false;
public AtomicTrieNode(Character ch) {
this.children.set(new HashMap<Character, TrieNode>());
this.character = ch;
}
public TrieNode getChild(Character c) {
return children.get().get(c);
}
public TrieNode getOrCreateChild(Character c) {
TrieNode node = children.get().get(c);
if (node == null) {
Map<Character, TrieNode> newChs;
do {
Map<Character, TrieNode> chs = children.get();
node = chs.get(c);
if (node != null) {
break;
}
newChs = Maps.newHashMap(chs);
node = new AtomicTrieNode(c);
newChs.put(c, node);
if (children.compareAndSet(chs, newChs)) {
break;
}
}
while (true);
}
return node;
}
public void setIsWord(boolean isWord) {
this.isWord = isWord;
}
public boolean isWord() {
return isWord;
}
@Override
public Character getCharacter() {
return this.character;
}
public void accept(TrieNodeVisitor visitor) {
List<TrieNode> nodes = Lists.newArrayList(children.get().values());
Collections.sort(nodes, new Comparator<TrieNode>() {
@Override
public int compare(TrieNode arg0, TrieNode arg1) {
return arg0.getCharacter().compareTo(arg1.getCharacter());
}
});
for (TrieNode node : nodes) {
visitor.visit(node);
}
}
}
public static class Trie {
private TrieNode root = new AtomicTrieNode(null);
public boolean addWord(String word) {
word = word.toUpperCase();
StringCharacterIterator iter = new StringCharacterIterator(word);
TrieNode current = root;
for (Character ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) {
current = current.getOrCreateChild(ch);
}
current.setIsWord(true);
return true;
}
public boolean containsWord(String word) {
word = word.toUpperCase();
StringCharacterIterator iter = new StringCharacterIterator(word);
TrieNode current = root;
for (Character ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) {
current = current.getChild(ch);
if (current == null)
return false;
}
return current.isWord();
}
public void accept(TrieNodeVisitor visitor) {
visitor.visit(root);
}
}
public static class SimpleTriePrinter implements TrieNodeVisitor {
private String prefix = "";
@Override
public void visit(TrieNode node) {
System.out.println(prefix + node.getCharacter());
prefix += " ";
node.accept(this);
prefix = StringUtils.substring(prefix, 1);
}
}
@Test
public void testTrie() {
String[] common = {"the","of","and","a","to","in","is","you","that","it","he","was","for","on","are","as","with","his","they","I","at","be","this","have","from","or","one","had","by","word","but","not","what","all","were","we","when","your","can","said","there","use","an","each","which","she","do","how","their","if","will","up","other","about","out","many","then","them","these","so","some","her","would","make","like","him","into","time","has","look","two","more","write","go","see","number","no","way","could","people","my","than","first","water","been","call","who","oil","its","now","find","long","down","day","did","get","come","made","may","part"};
Trie trie = new Trie();
for (String word : common) {
trie.addWord(word);
}
trie.accept(new SimpleTriePrinter());
}
}
| 3,318 |
0 |
Create_ds/staash/staash-core/src/test/java/com/netflix
|
Create_ds/staash/staash-core/src/test/java/com/netflix/paas/ArchaeusPassConfigurationTest.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
import java.lang.reflect.Method;
import org.apache.commons.lang.time.StopWatch;
import org.junit.Ignore;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.ProvidedBy;
import com.google.inject.Provider;
import com.netflix.config.ConfigurationManager;
import com.netflix.paas.config.annotations.Configuration;
import com.netflix.paas.config.annotations.DefaultValue;
import com.netflix.paas.config.annotations.Dynamic;
import com.netflix.paas.config.base.CglibArchaeusConfigurationFactory;
import com.netflix.paas.config.base.DynamicProxyArchaeusConfigurationFactory;
import com.netflix.paas.config.base.JavaAssistArchaeusConfigurationFactory;
public class ArchaeusPassConfigurationTest {
public class TestProxyProvider<T> implements Provider<T> {
private Class<T> type;
public TestProxyProvider(Class<T> type) {
this.type = type;
}
@Override
public T get() {
System.out.println("TestProxyProvider " + type.getCanonicalName());
return null;
}
}
public interface MyConfig {
@Configuration(value="test.property.dynamic.string")
@Dynamic
@DefaultValue("DefaultA")
String getDynamicString();
@Configuration(value="test.property.dynamic.int")
@DefaultValue("123")
@Dynamic
Integer getDynamicInt();
@Configuration(value="test.property.dynamic.boolean")
@DefaultValue("true")
@Dynamic
Boolean getDynamicBoolean();
@Configuration(value="test.property.dynamic.long")
@DefaultValue("456")
@Dynamic
Long getDynamicLong();
@Configuration(value="test.property.dynamic.double")
@DefaultValue("1.2")
@Dynamic
Double getDynamicDouble();
// @Configuration(value="test.property.supplier.string", defaultValue="suppliedstring", dynamic=true)
// Supplier<String> getDynamicStringSupplier();
@Configuration(value="test.property.static.string")
@DefaultValue("DefaultA")
String getStaticString();
@Configuration(value="test.property.static.int")
@DefaultValue("123")
Integer getStaticInt();
@Configuration(value="test.property.static.boolean")
@DefaultValue("true")
Boolean getStaticBoolean();
@Configuration(value="test.property.static.long")
@DefaultValue("456")
Long getStaticLong();
@Configuration(value="test.property.static.double")
@DefaultValue("1.2")
Double getStaticDouble();
}
@Test
@Ignore
public void test() throws Exception {
MyConfig config = new DynamicProxyArchaeusConfigurationFactory().get(MyConfig.class);
System.out.println("----- BEFORE -----");
printContents(config);
ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.string", "NewA");
ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.int", "321");
ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.boolean", "false");
ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.long", "654");
ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.double", "2.1");
ConfigurationManager.getConfigInstance().setProperty("test.property.static.string", "NewA");
ConfigurationManager.getConfigInstance().setProperty("test.property.static.int", "321");
ConfigurationManager.getConfigInstance().setProperty("test.property.static.boolean", "false");
ConfigurationManager.getConfigInstance().setProperty("test.property.static.long", "654");
ConfigurationManager.getConfigInstance().setProperty("test.property.static.double", "2.1");
System.out.println("----- AFTER -----");
printContents(config);
// Supplier<String> supplier = config.getDynamicStringSupplier();
// System.out.println("Supplier value : " + supplier.get());
int count = 1000000;
MyConfig configDynamicProxy = new DynamicProxyArchaeusConfigurationFactory().get(MyConfig.class);
MyConfig configJavaAssixt = new JavaAssistArchaeusConfigurationFactory().get(MyConfig.class);
MyConfig configCglib = new CglibArchaeusConfigurationFactory().get(MyConfig.class);
for (int i = 0; i < 10; i++) {
System.out.println("==== Run " + i + " ====");
timeConfig(configDynamicProxy, "Dynamic Proxy", count);
timeConfig(configJavaAssixt, "Java Assist ", count);
timeConfig(configCglib, "CGLIB ", count);
}
}
@Test
@Ignore
public void testWithInjection() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(MyConfig.class).toProvider(new TestProxyProvider<MyConfig>(MyConfig.class));
}
});
MyConfig config = injector.getInstance(MyConfig.class);
}
void timeConfig(MyConfig config, String name, int count) {
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < count; i++) {
for (Method method : MyConfig.class.getMethods()) {
try {
Object value = method.invoke(config);
// System.out.println(name + " " + method.getName() + " " + value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println(name + " took " + sw.getTime());
}
void printContents(MyConfig config) {
for (Method method : MyConfig.class.getMethods()) {
try {
System.out.println(method.getName() + " " + method.invoke(config));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 3,319 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/ByteBufferSerializer.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
public class ByteBufferSerializer {
}
| 3,320 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/PaasModule.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.commons.configuration.AbstractConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
import com.google.inject.spi.InjectionListener;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;
import com.netflix.config.ConfigurationManager;
import com.netflix.paas.config.ArchaeusPaasConfiguration;
import com.netflix.paas.config.PaasConfiguration;
import com.netflix.paas.dao.DaoProvider;
import com.netflix.paas.resources.DataResource;
import com.netflix.paas.resources.SchemaAdminResource;
import com.netflix.paas.resources.impl.JerseySchemaAdminResourceImpl;
import com.netflix.paas.service.SchemaService;
import com.netflix.paas.services.impl.DaoSchemaService;
import com.netflix.paas.tasks.InlineTaskManager;
import com.netflix.paas.tasks.TaskManager;
/**
* Core bindings for PAAS. Anything configurable will be loaded by different modules
* @author elandau
*
*/
public class PaasModule extends AbstractModule {
private static final Logger LOG = LoggerFactory.getLogger(PaasModule.class);
private final EventBus eventBus = new EventBus("Default EventBus");
@Override
protected void configure() {
LOG.info("Loading PaasModule");
bind(EventBus.class).toInstance(eventBus);
bindListener(Matchers.any(), new TypeListener() {
public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
typeEncounter.register(new InjectionListener<I>() {
public void afterInjection(I i) {
eventBus.register(i);
}
});
}
});
bind(TaskManager.class).to(InlineTaskManager.class);
// Constants
bind(String.class).annotatedWith(Names.named("namespace")).toInstance("com.netflix.pass.");
bind(String.class).annotatedWith(Names.named("appname" )).toInstance("paas");
bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance());
// Configuration
bind(PaasConfiguration.class).to(ArchaeusPaasConfiguration.class).in(Scopes.SINGLETON);
// Stuff
bind(ScheduledExecutorService.class).annotatedWith(Names.named("tasks")).toInstance(Executors.newScheduledThreadPool(10));
bind(DaoProvider.class).in(Scopes.SINGLETON);
// Rest resources
bind(DataResource.class).in(Scopes.SINGLETON);
bind(SchemaAdminResource.class).to(JerseySchemaAdminResourceImpl.class).in(Scopes.SINGLETON);
bind(SchemaService.class).to(DaoSchemaService.class).in(Scopes.SINGLETON);
}
}
| 3,321 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/ByteBufferDeserializer.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
public class ByteBufferDeserializer {
}
| 3,322 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/JsonSerializer.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.module.SimpleModule;
public class JsonSerializer {
final static ObjectMapper mapper = new ObjectMapper();
{
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
mapper.enableDefaultTyping();
}
public static <T> String toString(T entity) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mapper.writeValue(baos, entity);
baos.flush();
return baos.toString();
}
public static <T> T fromString(String data, Class<T> clazz) throws Exception {
return (T) mapper.readValue(
new ByteArrayInputStream(data.getBytes()),
clazz);
}
}
| 3,323 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/SchemaNames.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
public enum SchemaNames {
CONFIGURATION,META
}
| 3,324 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/PaasBootstrap.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.netflix.paas.dao.Dao;
import com.netflix.paas.dao.DaoProvider;
import com.netflix.paas.dao.DaoSchema;
import com.netflix.paas.entity.PassGroupConfigEntity;
import com.netflix.paas.entity.DbEntity;
import com.netflix.paas.resources.DataResource;
public class PaasBootstrap {
private static final Logger LOG = LoggerFactory.getLogger(PaasBootstrap.class);
@Inject
public PaasBootstrap(DaoProvider daoProvider) throws Exception {
LOG.info("Bootstrapping PAAS");
DaoSchema schemaDao = daoProvider.getSchema(SchemaNames.CONFIGURATION.name());
if (!schemaDao.isExists()) {
schemaDao.createSchema();
}
Dao<DbEntity> vschemaDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), DbEntity.class);
if (!vschemaDao.isExists()) {
vschemaDao.createTable();
}
Dao<PassGroupConfigEntity> groupDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), PassGroupConfigEntity.class);
if (!groupDao.isExists()) {
groupDao.createTable();
}
}
}
| 3,325 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/InlineTaskManager.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.tasks;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.Binding;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
public class InlineTaskManager implements TaskManager {
private final static Logger LOG = LoggerFactory.getLogger(InlineTaskManager.class);
private final Injector injector;
public static class SyncListenableFuture implements ListenableFuture<Void> {
private final Exception exception;
public SyncListenableFuture(Exception exception) {
this.exception = exception;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public Void get() throws InterruptedException, ExecutionException {
if (exception != null)
throw new ExecutionException("Very bad", exception);
return null;
}
@Override
public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (exception != null)
throw new ExecutionException("Very bad", exception);
return get();
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public void addListener(Runnable listener, Executor executor) {
}
}
@Inject
public InlineTaskManager(Injector injector, EventBus eventBus) {
this.injector = injector;
LOG.info("SyncTaskManager " + this.injector);
for (Entry<Key<?>, Binding<?>> key : this.injector.getBindings().entrySet()) {
LOG.info("SyncTaskManager " + key.toString());
}
}
@Override
public ListenableFuture<Void> submit(Class<?> clazz, Map<String, Object> args) {
Task task;
Exception exception = null;
TaskContext context = new TaskContext(clazz, args);
try {
LOG.info(clazz.getCanonicalName());
task = (Task) injector.getInstance(clazz);
task.execte(context);
} catch (Exception e) {
LOG.warn("Failed to execute task '{}'. '{}'", new Object[]{context.getKey(), e.getMessage(), e});
exception = e;
}
return new SyncListenableFuture(exception);
}
@Override
public ListenableFuture<Void> submit(Class<?> clazz) {
return submit(clazz, null);
}
}
| 3,326 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/TaskContext.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.tasks;
import java.util.Map;
public class TaskContext {
private final Map<String, Object> parameters;
private final String className;
public TaskContext(Class<?> className, Map<String, Object> arguments) {
this.className = className.getCanonicalName();
this.parameters = arguments;
}
public Object getParamater(String key) {
return this.parameters.get(key);
}
public String getStringParameter(String key) {
return (String)getParamater(key);
}
public String getStringParameter(String key, String defaultValue) {
Object value = getParamater(key);
return (value == null) ? defaultValue : (String)value;
}
public Boolean getBooleanParameter(String key) {
return (Boolean)getParamater(key);
}
public Boolean getBooleanParameter(String key, Boolean defaultValue) {
Object value = getParamater(key);
return (value == null) ? defaultValue : (Boolean)value;
}
public Integer getIntegerParameter(String key) {
return (Integer)getParamater(key);
}
public Integer getIntegerParameter(String key, Integer defaultValue) {
Object value = getParamater(key);
return (value == null) ? defaultValue : (Integer)value;
}
public Long getLongParameter(String key) {
return (Long)getParamater(key);
}
public Long getLongParameter(String key, Long defaultValue) {
Object value = getParamater(key);
return (value == null) ? defaultValue : (Long)value;
}
public String getClassName(String className) {
return this.className;
}
public String getKey() {
if (parameters == null || !parameters.containsKey("key"))
return className;
return className + "$" + parameters.get("key");
}
}
| 3,327 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/TaskManager.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.tasks;
import java.util.Map;
import com.google.common.util.concurrent.ListenableFuture;
public interface TaskManager {
ListenableFuture<Void> submit(Class<?> className);
ListenableFuture<Void> submit(Class<?> className, Map<String, Object> args);
}
| 3,328 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/Task.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.tasks;
public interface Task {
public void execte(TaskContext context) throws Exception;
}
| 3,329 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger/TableTrigger.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.trigger;
public interface TableTrigger {
void onDeleteRow(String schema, String table, String rowkey);
void onUpsertRow(String schema, String table, String rowkey);
}
| 3,330 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger/impl/HttpTableTrigger.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.trigger.impl;
import com.netflix.paas.trigger.TableTrigger;
public class HttpTableTrigger implements TableTrigger {
@Override
public void onDeleteRow(String schema, String table, String rowkey) {
// TODO Auto-generated method stub
}
@Override
public void onUpsertRow(String schema, String table, String rowkey) {
// TODO Auto-generated method stub
}
}
| 3,331 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger/impl/LoggingTableTrigger.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.trigger.impl;
import com.netflix.paas.trigger.TableTrigger;
public class LoggingTableTrigger implements TableTrigger {
@Override
public void onDeleteRow(String schema, String table, String rowkey) {
// TODO Auto-generated method stub
}
@Override
public void onUpsertRow(String schema, String table, String rowkey) {
// TODO Auto-generated method stub
}
}
| 3,332 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/jersey/NaturalNotationContextResolver.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.jersey;
import com.sun.jersey.api.json.JSONJAXBContext;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@Provider
class NaturalNotationContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
NaturalNotationContextResolver() {
try {
this.context = new JSONJAXBContext();
}
catch ( JAXBException e ) {
throw new RuntimeException(e);
}
}
public JAXBContext getContext(Class<?> objectType) {
return context;
}
}
| 3,333 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/jersey/JsonMessageBodyReader.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.jersey;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
@Consumes({"application/json"})
@Provider
public class JsonMessageBodyReader implements MessageBodyReader<Object> {
private final ObjectMapper mapper;
public JsonMessageBodyReader() {
mapper = new ObjectMapper();
// mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
}
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return mapper.canSerialize(type);
}
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> arg4, InputStream is) throws IOException, WebApplicationException {
return mapper.readValue(is, type);
}
}
| 3,334 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/jersey/JsonMessageBodyWriter.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.jersey;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
/**
* A MessageBodyWriter implementation that uses Jackson ObjectMapper to serialize objects to JSON.
*/
@Produces({"application/json"})
@Provider
public class JsonMessageBodyWriter implements MessageBodyWriter<Object> {
private final ObjectMapper mapper;
public JsonMessageBodyWriter() {
mapper = new ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
}
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return mapper.canSerialize(type);
}
public long getSize(Object data, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return -1;
}
public void writeTo(Object data, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out)
throws IOException, WebApplicationException {
mapper.writeValue(out, data);
out.flush();
}
}
| 3,335 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/util/Pair.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.util;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Pair<L, R> {
private final L left;
private final R right;
/**
* @param left
* @param right
*/
public Pair(L left, R right) {
Validate.notNull(left);
this.left = left;
Validate.notNull(right);
this.right = right;
}
/**
* @return L
*/
public L getLeft() {
return left;
}
/**
* @return R
*/
public R getRight() {
return right;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof Pair))
return false;
Pair<?,?> that = (Pair<?,?>) other;
return new EqualsBuilder().
append(this.left, that.left).
append(this.right, that.left).
isEquals();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder().
append(this.left).
append(this.right).
toHashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("(").
append(this.left).
append(",").
append(this.right).
append(")");
return sb.toString();
}
}
| 3,336 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/ConfigurationFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config;
import org.apache.commons.configuration.AbstractConfiguration;
import com.netflix.config.DynamicPropertyFactory;
/**
* Interface for creating a proxied Configuration of an interface which
* uses the Configuration annotation
*
* @author elandau
*/
public interface ConfigurationFactory {
/**
* Create an instance of the configuration interface using the default DynamicPropertyFactory and AbstractConfiguration
*
* @param configClass
* @return
* @throws Exception
*/
public <T> T get(Class<T> configClass) throws Exception;
/**
* Create an instance of the configuration interface
*
* @param configClass
* @param propertyFactory
* @param configuration
* @return
* @throws Exception
*/
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception;
}
| 3,337 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/PaasProperty.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config;
public enum PaasProperty implements GenericProperty {
TEST("test", "0")
;
PaasProperty(String name, String defaultValue) {
this.name = name;
this.defaultValue = defaultValue;
}
private final String name;
private final String defaultValue;
@Override
public String getName() {
return this.name;
}
@Override
public String getDefault() {
return defaultValue;
}
}
| 3,338 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/ArchaeusPaasConfiguration.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config;
import java.io.IOException;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.PropertyWrapper;
public class ArchaeusPaasConfiguration implements PaasConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(ArchaeusPaasConfiguration.class);
private static final DynamicStringProperty PAAS_PROPS_FILE = DynamicPropertyFactory.getInstance().getStringProperty("paas.client.props", "paas");
private final String namespace;
private static ConcurrentMap<String, PropertyWrapper<?>> parameters;
@Inject
public ArchaeusPaasConfiguration(@Named("namespace") String namespace) {
LOG.info("Created");
this.namespace = namespace;
}
@PostConstruct
public void initialize() {
LOG.info("Initializing");
String filename = PAAS_PROPS_FILE.get();
try {
ConfigurationManager.loadCascadedPropertiesFromResources(filename);
} catch (IOException e) {
LOG.warn(
"Cannot find the properties specified : {}. This may be okay if there are other environment specific properties or the configuration is installed with a different mechanism.",
filename);
}
}
@Override
public Integer getInteger(GenericProperty name) {
PropertyWrapper<Integer> prop = (PropertyWrapper<Integer>)parameters.get(name.getName());
if (prop == null) {
PropertyWrapper<Integer> newProp = DynamicPropertyFactory.getInstance().getIntProperty(namespace + name, Integer.parseInt(name.getDefault()));
prop = (PropertyWrapper<Integer>) parameters.putIfAbsent(name.getName(), newProp);
if (prop == null)
prop = newProp;
}
return prop.getValue();
}
@Override
public String getString(GenericProperty name) {
PropertyWrapper<String> prop = (PropertyWrapper<String>)parameters.get(name.getName());
if (prop == null) {
PropertyWrapper<String> newProp = DynamicPropertyFactory.getInstance().getStringProperty(namespace + name, name.getDefault());
prop = (PropertyWrapper<String>) parameters.putIfAbsent(name.getName(), newProp);
if (prop == null)
prop = newProp;
}
return prop.getValue();
}
@Override
public Boolean getBoolean(GenericProperty name) {
PropertyWrapper<Boolean> prop = (PropertyWrapper<Boolean>)parameters.get(name.getName());
if (prop == null) {
PropertyWrapper<Boolean> newProp = DynamicPropertyFactory.getInstance().getBooleanProperty(namespace + name, Boolean.parseBoolean(name.getDefault()));
prop = (PropertyWrapper<Boolean>) parameters.putIfAbsent(name.getName(), newProp);
if (prop == null)
prop = newProp;
}
return prop.getValue();
}
@Override
public Long getLong(GenericProperty name) {
PropertyWrapper<Long> prop = (PropertyWrapper<Long>)parameters.get(name.getName());
if (prop == null) {
PropertyWrapper<Long> newProp = DynamicPropertyFactory.getInstance().getLongProperty(namespace + name, Long.parseLong(name.getDefault()));
prop = (PropertyWrapper<Long>) parameters.putIfAbsent(name.getName(), newProp);
if (prop == null)
prop = newProp;
}
return prop.getValue();
}
@Override
public Double getDouble(GenericProperty name) {
PropertyWrapper<Double> prop = (PropertyWrapper<Double>)parameters.get(name.getName());
if (prop == null) {
PropertyWrapper<Double> newProp = DynamicPropertyFactory.getInstance().getDoubleProperty(namespace + name, Double.parseDouble(name.getDefault()));
prop = (PropertyWrapper<Double>) parameters.putIfAbsent(name.getName(), newProp);
if (prop == null)
prop = newProp;
}
return prop.getValue();
}
}
| 3,339 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/GenericProperty.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config;
public interface GenericProperty {
String getName();
String getDefault();
}
| 3,340 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/PaasConfiguration.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config;
public interface PaasConfiguration {
public Integer getInteger(GenericProperty name);
public String getString(GenericProperty name);
public Boolean getBoolean(GenericProperty name);
public Double getDouble(GenericProperty name);
public Long getLong(GenericProperty name);
}
| 3,341 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/ConfigurationProxyFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config;
public interface ConfigurationProxyFactory {
}
| 3,342 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/ProxyConfig.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ProxyConfig {
}
| 3,343 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/Configuration.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Configuration {
String value() default "";
String documentation() default "";
}
| 3,344 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/Dynamic.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Dynamic {
}
| 3,345 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/DefaultValue.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultValue {
String value();
}
| 3,346 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/DynamicProxyArchaeusConfigurationFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.base;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import net.sf.cglib.proxy.Enhancer;
import org.apache.commons.configuration.AbstractConfiguration;
import com.google.common.base.Supplier;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.paas.config.ConfigurationFactory;
public class DynamicProxyArchaeusConfigurationFactory implements ConfigurationFactory {
@Override
public <T> T get(Class<T> configClass) throws Exception {
return get(configClass,
DynamicPropertyFactory.getInstance(),
ConfigurationManager.getConfigInstance());
}
@SuppressWarnings({ "unchecked", "static-access" })
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception {
final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration);
if (configClass.isInterface()) {
Class<?> proxyClass = Proxy.getProxyClass(
configClass.getClassLoader(), new Class[] { configClass });
return (T) proxyClass
.getConstructor(new Class[] { InvocationHandler.class })
.newInstance(new Object[] { new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Supplier<?> supplier = (Supplier<?>)methods.get(method.getName());
return supplier.get();
}
}});
}
else {
final Enhancer enhancer = new Enhancer();
final Object obj = (T) enhancer.create(configClass,
new net.sf.cglib.proxy.InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Supplier<?> supplier = (Supplier<?>)methods.get(method.getName());
if (supplier == null) {
return method.invoke(proxy, args);
}
return supplier.get();
}
});
ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration);
return (T)obj;
}
}
}
| 3,347 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/ProxyConfigProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.base;
import com.google.inject.Provider;
public class ProxyConfigProvider implements Provider<Object> {
@Override
public Object get() {
System.out.println("ProxyConfigProvider");
return null;
}
}
| 3,348 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/CglibArchaeusConfigurationFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.base;
import java.lang.reflect.Method;
import java.util.Map;
import org.apache.commons.configuration.AbstractConfiguration;
import com.google.common.base.Supplier;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.paas.config.ConfigurationFactory;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
public class CglibArchaeusConfigurationFactory implements ConfigurationFactory {
@Override
public <T> T get(Class<T> configClass) throws Exception {
return get(configClass,
DynamicPropertyFactory.getInstance(),
ConfigurationManager.getConfigInstance());
}
@SuppressWarnings({ "unchecked", "static-access" })
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception {
final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration);
if (configClass.isInterface()) {
final Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(configClass);
enhancer.setCallback(new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Supplier<?> supplier = (Supplier<?>)methods.get(method.getName());
return supplier.get();
}
});
return (T) enhancer.create();
}
else {
final Enhancer enhancer = new Enhancer();
final Object obj = (T) enhancer.create(configClass,
new net.sf.cglib.proxy.InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Supplier<?> supplier = (Supplier<?>)methods.get(method.getName());
if (supplier == null) {
return method.invoke(proxy, args);
}
return supplier.get();
}
});
ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration);
return (T)obj;
}
}
}
| 3,349 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/ConfigurationProxyUtils.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.base;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Maps;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.PropertyWrapper;
import com.netflix.governator.annotations.Configuration;
import com.netflix.paas.config.annotations.DefaultValue;
import com.netflix.paas.config.annotations.Dynamic;
import java.lang.reflect.Field;
import org.apache.commons.configuration.AbstractConfiguration;
/**
* Utility class used by ConfigurationProxyFactory implementations to proxy methods of a
* configuration interface using information from the Configuration annotation
*
* @author elandau
*/
public class ConfigurationProxyUtils {
public static class PropertyWrapperSupplier<T> implements Supplier<T> {
private final PropertyWrapper<T> wrapper;
public PropertyWrapperSupplier(PropertyWrapper<T> wrapper) {
this.wrapper = wrapper;
}
@Override
public T get() {
return this.wrapper.getValue();
}
}
static Supplier<?> getDynamicSupplier(Class<?> type, String key, String defaultValue, DynamicPropertyFactory propertyFactory) {
if (type.isAssignableFrom(String.class)) {
return new PropertyWrapperSupplier<String>(
propertyFactory.getStringProperty(
key,
defaultValue));
}
else if (type.isAssignableFrom(Integer.class)) {
return new PropertyWrapperSupplier<Integer>(
propertyFactory.getIntProperty(
key,
defaultValue == null ? 0 : Integer.parseInt(defaultValue)));
}
else if (type.isAssignableFrom(Double.class)) {
return new PropertyWrapperSupplier<Double>(
propertyFactory.getDoubleProperty(
key,
defaultValue == null ? 0.0 : Double.parseDouble(defaultValue)));
}
else if (type.isAssignableFrom(Long.class)) {
return new PropertyWrapperSupplier<Long>(
propertyFactory.getLongProperty(
key,
defaultValue == null ? 0L : Long.parseLong(defaultValue)));
}
else if (type.isAssignableFrom(Boolean.class)) {
return new PropertyWrapperSupplier<Boolean>(
propertyFactory.getBooleanProperty(
key,
defaultValue == null ? false : Boolean.parseBoolean(defaultValue)));
}
throw new RuntimeException("Unsupported value type " + type.getCanonicalName());
}
static Supplier<?> getStaticSupplier(Class<?> type, String key, String defaultValue, AbstractConfiguration configuration) {
if (type.isAssignableFrom(String.class)) {
return Suppliers.ofInstance(
configuration.getString(
key,
defaultValue));
}
else if (type.isAssignableFrom(Integer.class)) {
return Suppliers.ofInstance(
configuration.getInteger(
key,
defaultValue == null ? 0 : Integer.parseInt(defaultValue)));
}
else if (type.isAssignableFrom(Double.class)) {
return Suppliers.ofInstance(
configuration.getDouble(
key,
defaultValue == null ? 0.0 : Double.parseDouble(defaultValue)));
}
else if (type.isAssignableFrom(Long.class)) {
return Suppliers.ofInstance(
configuration.getLong(
key,
defaultValue == null ? 0L : Long.parseLong(defaultValue)));
}
else if (type.isAssignableFrom(Boolean.class)) {
return Suppliers.ofInstance(
configuration.getBoolean(
key,
defaultValue == null ? false : Boolean.parseBoolean(defaultValue)));
}
throw new RuntimeException("Unsupported value type " + type.getCanonicalName());
}
static String getPropertyName(Method method, Configuration c) {
String name = c.value();
if (name.isEmpty()) {
name = method.getName();
name = StringUtils.removeStart(name, "is");
name = StringUtils.removeStart(name, "get");
name = name.toLowerCase();
}
return name;
}
static String getPropertyName(Field field, Configuration c) {
String name = c.value();
if (name.isEmpty()) {
return field.getName();
}
return name;
}
static <T> Map<String, Supplier<?>> getMethodSuppliers(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) {
final Map<String, Supplier<?>> properties = Maps.newHashMap();
for (Method method : configClass.getMethods()) {
Configuration c = method.getAnnotation(Configuration.class);
if (c == null)
continue;
String defaultValue = null;
DefaultValue dv = method.getAnnotation(DefaultValue.class);
if (dv != null)
defaultValue = dv.value();
String name = getPropertyName(method, c);
if (method.getReturnType().isAssignableFrom(Supplier.class)) {
Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Class<?> actualType = (Class<?>)type.getActualTypeArguments()[0];
properties.put(method.getName(),
method.getAnnotation(Dynamic.class) != null
? Suppliers.ofInstance(getDynamicSupplier(actualType, name, defaultValue, propertyFactory))
: Suppliers.ofInstance(getStaticSupplier(actualType, name, defaultValue, configuration)));
}
else {
throw new RuntimeException("We'll get to this later");
}
}
else {
properties.put(method.getName(),
method.getAnnotation(Dynamic.class) != null
? getDynamicSupplier(method.getReturnType(), name, defaultValue, propertyFactory)
: getStaticSupplier (method.getReturnType(), name, defaultValue, configuration));
}
}
return properties;
}
static void assignFieldValues(final Object obj, Class<?> type, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception {
// Iterate through all fields and set initial value as well as set up dynamic properties
// where necessary
for (final Field field : type.getFields()) {
Configuration c = field.getAnnotation(Configuration.class);
if (c == null)
continue;
String defaultValue = field.get(obj).toString();
String name = ConfigurationProxyUtils.getPropertyName(field, c);
Supplier<?> supplier = ConfigurationProxyUtils.getStaticSupplier(field.getType(), name, defaultValue, configuration);
field.set(obj, supplier.get());
if (field.getAnnotation(Dynamic.class) != null) {
final PropertyWrapper<?> property;
if (field.getType().isAssignableFrom(String.class)) {
property = propertyFactory.getStringProperty(
name,
defaultValue);
}
else if (field.getType().isAssignableFrom(Integer.class)) {
property = propertyFactory.getIntProperty(
name,
defaultValue == null ? 0 : Integer.parseInt(defaultValue));
}
else if (field.getType().isAssignableFrom(Double.class)) {
property = propertyFactory.getDoubleProperty(
name,
defaultValue == null ? 0.0 : Double.parseDouble(defaultValue));
}
else if (field.getType().isAssignableFrom(Long.class)) {
property = propertyFactory.getLongProperty(
name,
defaultValue == null ? 0L : Long.parseLong(defaultValue));
}
else if (field.getType().isAssignableFrom(Boolean.class)) {
property = propertyFactory.getBooleanProperty(
name,
defaultValue == null ? false : Boolean.parseBoolean(defaultValue));
}
else {
throw new RuntimeException("Unsupported type " + field.getType());
}
property.addCallback(new Runnable() {
@Override
public void run() {
try {
field.set(obj, property.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
}
| 3,350 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/JavaAssistArchaeusConfigurationFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.config.base;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import net.sf.cglib.proxy.Enhancer;
import org.apache.commons.configuration.AbstractConfiguration;
import com.google.common.base.Supplier;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.paas.config.ConfigurationFactory;
public class JavaAssistArchaeusConfigurationFactory implements ConfigurationFactory {
@Override
public <T> T get(Class<T> configClass) throws Exception {
return get(configClass,
DynamicPropertyFactory.getInstance(),
ConfigurationManager.getConfigInstance());
}
@SuppressWarnings({ "unchecked", "static-access" })
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception {
final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration);
if (configClass.isInterface()) {
Class<?> proxyClass = Proxy.getProxyClass(
configClass.getClassLoader(), new Class[] { configClass });
return (T) proxyClass
.getConstructor(new Class[] { InvocationHandler.class })
.newInstance(new Object[] { new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Supplier<?> supplier = (Supplier<?>)methods.get(method.getName());
if (supplier == null) {
return method.invoke(proxy, args);
}
return supplier.get();
}
}});
}
else {
final Enhancer enhancer = new Enhancer();
final Object obj = (T) enhancer.create(configClass,
new net.sf.cglib.proxy.InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Supplier<?> supplier = (Supplier<?>)methods.get(method.getName());
if (supplier == null) {
return method.invoke(proxy, args);
}
return supplier.get();
}
});
ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration);
return (T)obj;
}
}
}
| 3,351 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/TableEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.google.common.collect.Maps;
/**
* Definition for a table in the system. This definition provides this system will
* all the information for connecting to the target persistence implementation
*
* @author elandau
*
*/
@Entity
public class TableEntity {
public static class Builder {
private TableEntity entity = new TableEntity();
public Builder withStorageType(String type) {
entity.storageType = type;
return this;
}
public Builder withTableName(String tableName) {
entity.tableName = tableName;
return this;
}
public Builder withSchemaName(String schema) {
entity.schema = schema;
return this;
}
public Builder withOptions(Map<String, String> options) {
entity.options = options;
return this;
}
public Builder withOption(String key, String value) {
if (entity.options == null) {
entity.options = Maps.newHashMap();
}
entity.options.put(key, value);
return this;
}
public TableEntity build() {
return entity;
}
}
public static Builder builder() {
return new Builder();
}
/**
* Unique table name within the schema
*/
@Id
private String tableName;
/**
* Type of storage for this table. (ex. cassandra)
*/
@Column(name="type")
private String storageType;
/**
* Parent schema
*/
@Column(name="schema")
private String schema;
/**
* Additional configuration options for the table. These parameters are normally
* specific to the underlying persistence technology
*/
@Column(name="options")
private Map<String, String> options;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getStorageType() {
return storageType;
}
public void setStorageType(String storageType) {
this.storageType = storageType;
}
public Map<String, String> getOptions() {
return options;
}
public void setOptions(Map<String, String> options) {
this.options = options;
}
public String getOption(String option) {
return getOption(option, null);
}
public String getOption(String key, String defaultValue) {
if (this.options == null)
return defaultValue;
String value = options.get(key);
if (value == null)
return defaultValue;
return value;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
@Override
public String toString() {
return "VirtualTableEntity [tableName=" + tableName + ", storageType=" + storageType + ", schema=" + schema + ", options="
+ options + "]";
}
}
| 3,352 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/RackEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class RackEntity {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 3,353 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/DbEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
import java.util.Map;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Transient;
import com.google.common.collect.Maps;
/**
* Definition of a global schema in the system. A schema may contain
* tables that are implemented using different technologies.
*
* @author elandau
*/
@Entity(name="db")
public class DbEntity {
public static class Builder {
private DbEntity entity = new DbEntity();
public Builder withName(String name) {
entity.name = name;
return this;
}
public Builder addTable(TableEntity table) throws Exception {
if (null == entity.getTables()) {
entity.tables = Maps.newHashMap();
}
entity.tables.put(table.getTableName(), table);
return this;
}
public Builder withOptions(Map<String, String> options) {
entity.options = options;
return this;
}
public Builder addOption(String name, String value) {
if (null == entity.getOptions()) {
entity.options = Maps.newHashMap();
}
entity.options.put(name, value);
return this;
}
public DbEntity build() {
return entity;
}
}
public static Builder builder() {
return new Builder();
}
@Id
private String name;
@Column
private Set<String> tableNames;
@Column
private Map<String, String> options;
@Transient
private Map<String, TableEntity> tables;
public Map<String, String> getOptions() {
return options;
}
public void setOptions(Map<String, String> options) {
this.options = options;
}
@PrePersist
private void prePersist() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setTables(Map<String, TableEntity> tables) {
this.tables = tables;
}
public Map<String, TableEntity> getTables() {
return tables;
}
public void setTableNames(Set<String> tableNames) {
this.tableNames = tableNames;
}
public Set<String> getTableNames() {
return tableNames;
}
public boolean hasTables() {
return this.tables != null && !this.tables.isEmpty();
}
@Override
public String toString() {
return "SchemaEntity [name=" + name + ", tables=" + tables + "]";
}
}
| 3,354 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/PassGroupConfigEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
import java.util.Collection;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.google.common.collect.Sets;
@Entity
public class PassGroupConfigEntity {
public static class Builder {
private PassGroupConfigEntity entity = new PassGroupConfigEntity();
public Builder withName(String name) {
entity.deploymentName = name;
return this;
}
public Builder withSchemas(Collection<String> names) {
if (entity.schemas == null) {
entity.schemas = Sets.newHashSet();
}
entity.schemas.addAll(names);
return this;
}
public Builder addSchema(String vschemaName) {
if (entity.schemas == null) {
entity.schemas = Sets.newHashSet();
}
entity.schemas.add(vschemaName);
return this;
}
public PassGroupConfigEntity build() {
return entity;
}
}
public static Builder builder() {
return new Builder();
}
@Id
private String deploymentName;
@Column
private Set<String> schemas;
public String getDeploymentName() {
return deploymentName;
}
public void setDeploymentName(String deploymentName) {
this.deploymentName = deploymentName;
}
public Set<String> getSchemas() {
return schemas;
}
public void setSchemas(Set<String> schemas) {
this.schemas = schemas;
}
@Override
public String toString() {
return "PassGroupConfigEntity [deploymentName=" + deploymentName + ", schemas=" + schemas + "]";
}
}
| 3,355 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/TableTriggerEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class TableTriggerEntity {
}
| 3,356 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ColumnMetadataEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
import java.util.List;
public class ColumnMetadataEntity {
private String type;
private String name;
private List<ColumnValidatorEntity> validator;
private List<ColumnIndexEntity> indexes;
}
| 3,357 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ColumnValidatorEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class ColumnValidatorEntity {
}
| 3,358 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/EntityIterable.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public interface EntityIterable<T> extends Iterable<T> {
}
| 3,359 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/SchemaTrigger.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class SchemaTrigger {
}
| 3,360 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/DatacenterEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class DatacenterEntity {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 3,361 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ClusterEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.google.common.collect.Sets;
@Entity(name="cluster")
public class ClusterEntity {
public static class Builder {
private ClusterEntity entity = new ClusterEntity();
public Builder withName(String name) {
entity.name = name;
return this;
}
public Builder withNodes(Set<String> nodes) {
entity.nodes = nodes;
return this;
}
public Builder addNode(String node) {
if (entity.nodes == null)
entity.nodes = Sets.newHashSet();
entity.nodes.add(node);
return this;
}
public ClusterEntity build() {
return entity;
}
}
public static Builder builder() {
return new Builder();
}
@Id
@Column
private String name;
@Column
private Set<String> nodes;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getNodes() {
return nodes;
}
public void setNodes(Set<String> nodes) {
this.nodes = nodes;
}
}
| 3,362 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ColumnIndexEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class ColumnIndexEntity {
}
| 3,363 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/TriggerEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.entity;
public class TriggerEntity {
}
| 3,364 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/TableDataResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.netflix.paas.data.QueryResult;
import com.netflix.paas.data.RowData;
import com.netflix.paas.exceptions.NotFoundException;
import com.netflix.paas.exceptions.PaasException;
import com.netflix.paas.json.JsonObject;
/**
* Interface for access to a table. Concrete implementation may implement a table
* on top of any persistence technology.
*
* @author elandau
*
*/
//@Path("/v1/data")
public interface TableDataResource {
// Table level API
@GET
public QueryResult listRows(
String cursor,
Integer rowLimit,
Integer columnLimit
) throws PaasException;
@DELETE
public void truncateRows(
) throws PaasException;
// Row level API
@GET
@Path("{key}")
public QueryResult readRow(
@PathParam("key") String key,
@QueryParam("count") @DefaultValue("0") Integer columnCount,
@QueryParam("start") @DefaultValue("") String startColumn,
@QueryParam("end") @DefaultValue("") String endColumn,
@QueryParam("reversed") @DefaultValue("false") Boolean reversed
) throws PaasException;
@DELETE
@Path("{key}")
public void deleteRow(
@PathParam("key") String key
) throws PaasException;
@POST
@Path("{db}/{table}")
@Consumes(MediaType.TEXT_PLAIN)
public void updateRow(
@PathParam("db") String db,
@PathParam("table") String table,
JsonObject rowData
) throws PaasException ;
// Row level API
@GET
@Path("{key}/{column}")
public QueryResult readColumn(
@PathParam("key") String key,
@PathParam("column") String column
) throws PaasException, NotFoundException;
@POST
@Path("{key}/{column}")
public void updateColumn(
@PathParam("key") String key,
@PathParam("column") String column,
String value
) throws PaasException, NotFoundException;
@DELETE
@Path("{key}/{column}")
public void deleteColumn(
@PathParam("key") String key,
@PathParam("column") String column
) throws PaasException;
// TODO: Batch operations
// TODO: Pagination
// TODO: Index search
}
| 3,365 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/SchemaAdminResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import com.netflix.paas.entity.DbEntity;
import com.netflix.paas.entity.TableEntity;
/**
* Admin resource for managing schemas
*/
@Path("/v1/admin")
public interface SchemaAdminResource {
/**
* List all schemas
*/
@GET
public String listSchemas();
/**
* Create a new schema
*/
@POST
@Consumes(MediaType.TEXT_PLAIN)
// @Path("/db")
public void createSchema(String payLd);
/**
* Delete an existing schema
* @param schemaName
*/
@DELETE
@Path("{schema}")
public void deleteSchema(@PathParam("schema") String schemaName);
/**
* Update an existing schema
* @param schemaName
* @param schema
*/
@POST
@Path("{schema}")
public void updateSchema(@PathParam("schema") String schemaName, DbEntity schema);
/**
* Get details for a schema
* @param schemaName
* @return
*/
@GET
@Path("{schema}")
public DbEntity getSchema(@PathParam("schema") String schemaName);
/**
* Get details for a subtable of schema
* @param schemaName
* @param tableName
*/
@GET
@Path("{schema}/tables/{table}")
public TableEntity getTable(@PathParam("schema") String schemaName, @PathParam("table") String tableName);
/**
* Remove a table from the schema
* @param schemaName
* @param tableName
*/
@DELETE
@Path("{schema}/tables/{table}")
public void deleteTable(@PathParam("schema") String schemaName, @PathParam("table") String tableName);
/**
* Create a table in the schema
* @param schemaName
* @param table
*/
@POST
@Path("{schema}")
@Consumes(MediaType.TEXT_PLAIN)
public void createTable(@PathParam("schema") String schemaName, String table);
/**
* Update an existing table in the schema
* @param schemaName
* @param tableName
* @param table
*/
@POST
@Path("{schema}/tables/{table}")
public void updateTable(@PathParam("schema") String schemaName, @PathParam("table") String tableName, TableEntity table);
}
| 3,366 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/PaasDataResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import com.netflix.paas.exceptions.PaasException;
import com.netflix.paas.json.JsonObject;
@Path("/v1/data")
public interface PaasDataResource {
@POST
@Path("{db}/{table}")
@Consumes(MediaType.TEXT_PLAIN)
public void updateRow(
@PathParam("db") String db,
@PathParam("table") String table,
String rowData
) ;
@GET
@Path("{db}/{table}/{keycol}/{key}")
public String listRow(@PathParam("db") String db,
@PathParam("table") String table, @PathParam("keycol") String keycol,@PathParam("key") String key);
String listSchemas();
}
| 3,367 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/DataResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.netflix.paas.events.SchemaChangeEvent;
import com.netflix.paas.exceptions.NotFoundException;
import com.netflix.paas.provider.TableDataResourceFactory;
@Path("/v1/datares")
public class DataResource {
private static final Logger LOG = LoggerFactory.getLogger(DataResource.class);
private volatile HashMap<String, DbDataResource> schemaResources = Maps.newHashMap();
private final Map<String, TableDataResourceFactory> tableDataResourceFactories;
@Inject
public DataResource(Map<String, TableDataResourceFactory> tableDataResourceFactories) {
LOG.info("Creating DataResource");
this.tableDataResourceFactories = tableDataResourceFactories;
Preconditions.checkArgument(!tableDataResourceFactories.isEmpty(), "No TableDataResourceFactory instances exists.");
}
/**
* Notification that a schema change was auto identified. We recreate the entire schema
* structure for the REST API.
* @param event
*/
@Subscribe
public synchronized void schemaChangeEvent(SchemaChangeEvent event) {
LOG.info("Schema changed " + event.getSchema().getName());
DbDataResource resource = new DbDataResource(event.getSchema(), tableDataResourceFactories);
HashMap<String, DbDataResource> newResources = Maps.newHashMap(schemaResources);
newResources.put(event.getSchema().getName(), resource);
schemaResources = newResources;
}
// Root API
// @GET
// public List<SchemaEntity> listSchemas() {
//// LOG.info("");
//// LOG.info("listSchemas");
//// return Lists.newArrayList(schemaService.listSchema());
// return null;
// }
@GET
@Produces("text/plain")
public String hello() {
return "hello";
}
@Path("{schema}")
public DbDataResource getSchemaDataResource(
@PathParam("schema") String schemaName
) throws NotFoundException {
DbDataResource resource = schemaResources.get(schemaName);
if (resource == null) {
throw new NotFoundException(DbDataResource.class, schemaName);
}
return resource;
}
}
| 3,368 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/TriggerResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import java.util.List;
import com.netflix.paas.entity.TriggerEntity;
public interface TriggerResource {
void createTableTrigger(String schema, String table, String name, TriggerEntity trigger);
void deleteTableTrigger(String schema, String table, String trigger);
List<TriggerEntity> listTableTriggers(String schema, String table);
List<TriggerEntity> listSchemaTriggers(String schema);
List<TriggerEntity> listAllTriggers();
}
| 3,369 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/BootstrapResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import java.util.List;
import javax.ws.rs.Path;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.netflix.paas.SchemaNames;
import com.netflix.paas.dao.Dao;
import com.netflix.paas.dao.DaoSchema;
import com.netflix.paas.dao.DaoSchemaProvider;
import com.netflix.paas.dao.DaoProvider;
import com.netflix.paas.dao.DaoStatus;
import com.netflix.paas.exceptions.NotFoundException;
@Path("/1/setup")
@Singleton
/**
* API to set up storage for the PAAS application
*
* @author elandau
*/
public class BootstrapResource {
private DaoProvider daoProvider;
@Inject
public BootstrapResource(DaoProvider daoProvider) {
this.daoProvider = daoProvider;
}
@Path("storage/create")
public void createStorage() throws NotFoundException {
DaoSchema schema = daoProvider.getSchema(SchemaNames.CONFIGURATION.name());
if (!schema.isExists()) {
schema.createSchema();
}
for (Dao<?> dao : schema.listDaos()) {
dao.createTable();
}
}
@Path("storage/status")
public List<DaoStatus> getStorageStatus() throws NotFoundException {
return Lists.newArrayList(Collections2.transform(
daoProvider.getSchema(SchemaNames.CONFIGURATION.name()).listDaos(),
new Function<Dao<?>, DaoStatus>() {
@Override
public DaoStatus apply(Dao<?> dao) {
return dao;
}
}));
}
}
| 3,370 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/DbDataResource.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources;
import java.util.Collection;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.netflix.paas.entity.DbEntity;
import com.netflix.paas.entity.TableEntity;
import com.netflix.paas.exceptions.NotFoundException;
import com.netflix.paas.provider.TableDataResourceFactory;
/**
* REST interface to a specific schema. This interface provides access to multiple tables
*
* @author elandau
*/
public class DbDataResource {
private static final Logger LOG = LoggerFactory.getLogger(DbDataResource.class);
private final Map<String, TableDataResourceFactory> tableDataResourceFactories;
private final DbEntity schemaEntity;
private final ImmutableMap<String, TableDataResource> tables;
public DbDataResource(DbEntity schemaEntity, Map<String, TableDataResourceFactory> tableDataResourceFactories) {
this.tableDataResourceFactories = tableDataResourceFactories;
this.schemaEntity = schemaEntity;
ImmutableMap.Builder<String, TableDataResource> builder = ImmutableMap.builder();
for (TableEntity table : schemaEntity.getTables().values()) {
LOG.info("Adding table '{}' to schema '{}'", new Object[]{table.getTableName(), schemaEntity.getName()});
try {
Preconditions.checkNotNull(table.getStorageType());
TableDataResourceFactory tableDataResourceFactory = tableDataResourceFactories.get(table.getStorageType());
if (tableDataResourceFactory == null) {
throw new NotFoundException(TableDataResourceFactory.class, table.getStorageType());
}
builder.put(table.getTableName(), tableDataResourceFactory.getTableDataResource(table));
}
catch (Exception e) {
LOG.error("Failed to create storage for table '{}' in schema '{}", new Object[]{table.getTableName(), schemaEntity.getName(), e});
}
}
tables = builder.build();
}
@GET
public Collection<TableEntity> listTables() {
return schemaEntity.getTables().values();
}
@Path("{table}")
public TableDataResource getTableSubresource(@PathParam("table") String tableName) throws NotFoundException {
TableDataResource resource = tables.get(tableName);
if (resource == null) {
throw new NotFoundException(TableDataResource.class, tableName);
}
return resource;
}
}
| 3,371 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/impl/JerseySchemaAdminResourceImpl.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources.impl;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import com.google.inject.Inject;
import com.netflix.paas.dao.DaoProvider;
import com.netflix.paas.entity.DbEntity;
import com.netflix.paas.entity.TableEntity;
import com.netflix.paas.json.JsonObject;
import com.netflix.paas.meta.dao.MetaDao;
import com.netflix.paas.meta.entity.PaasDBEntity;
import com.netflix.paas.meta.entity.PaasTableEntity;
import com.netflix.paas.resources.SchemaAdminResource;
public class JerseySchemaAdminResourceImpl implements SchemaAdminResource {
private DaoProvider provider;
private MetaDao metadao;
@Inject
public JerseySchemaAdminResourceImpl(DaoProvider provider, MetaDao meta) {
this.provider = provider;
this.metadao = meta;
}
@Override
@GET
public String listSchemas() {
// TODO Auto-generated method stub
return "hello";
}
@Override
public void createSchema(String payLoad) {
// TODO Auto-generated method stub
if (payLoad!=null) {
JsonObject jsonPayLoad = new JsonObject(payLoad);
PaasDBEntity pdbe = PaasDBEntity.builder().withJsonPayLoad(jsonPayLoad).build();
metadao.writeMetaEntity(pdbe);
// Dao<DbEntity> dbDao = provider.getDao("configuration", DbEntity.class);
// DbEntity dbe = DbEntity.builder().withName(schema.getString("name")).build();
// boolean exists = dbDao.isExists();
// dbDao.write(dbe);
// System.out.println("schema created");
// System.out.println("schema name is "+schema.getFieldNames()+" "+schema.toString());
}
}
@Override
@DELETE
@Path("{schema}")
public void deleteSchema(@PathParam("schema") String schemaName) {
// TODO Auto-generated method stub
}
@Override
@POST
@Path("{schema}")
public void updateSchema(@PathParam("schema") String schemaName, DbEntity schema) {
// TODO Auto-generated method stub
}
@Override
@GET
@Path("{schema}")
public DbEntity getSchema(@PathParam("schema") String schemaName) {
// TODO Auto-generated method stub
return null;
}
@Override
@GET
@Path("{schema}/tables/{table}")
public TableEntity getTable(@PathParam("schema") String schemaName, @PathParam("table") String tableName) {
// TODO Auto-generated method stub
return null;
}
@Override
@DELETE
@Path("{schema}/tables/{table}")
public void deleteTable(@PathParam("schema") String schemaName, @PathParam("table") String tableName) {
// TODO Auto-generated method stub
}
@Override
public void createTable(@PathParam("schema") String schemaName, String payLoad) {
// TODO Auto-generated method stub
if (payLoad!=null) {
JsonObject jsonPayLoad = new JsonObject(payLoad);
PaasTableEntity ptbe = PaasTableEntity.builder().withJsonPayLoad(jsonPayLoad, schemaName).build();
metadao.writeMetaEntity(ptbe);
//create new ks
//create new cf
}
}
@Override
@POST
@Path("{schema}/tables/{table}")
public void updateTable(@PathParam("schema") String schemaName, @PathParam("table") String tableName, TableEntity table) {
// TODO Auto-generated method stub
}
}
| 3,372 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/impl/JerseySchemaDataResourceImpl.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.resources.impl;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.google.inject.Inject;
import com.netflix.paas.dao.DaoProvider;
import com.netflix.paas.data.QueryResult;
import com.netflix.paas.data.RowData;
import com.netflix.paas.exceptions.NotFoundException;
import com.netflix.paas.exceptions.PaasException;
import com.netflix.paas.json.JsonObject;
import com.netflix.paas.meta.dao.MetaDao;
import com.netflix.paas.resources.PaasDataResource;
import com.netflix.paas.resources.TableDataResource;
public class JerseySchemaDataResourceImpl implements PaasDataResource {
private DaoProvider provider;
private MetaDao metadao;
@Inject
public JerseySchemaDataResourceImpl(DaoProvider provider, MetaDao meta) {
this.provider = provider;
this.metadao = meta;
}
@Override
@GET
public String listSchemas() {
// TODO Auto-generated method stub
return "hello data";
}
@Override
@GET
@Path("{db}/{table}/{keycol}/{key}")
public String listRow(@PathParam("db") String db,
@PathParam("table") String table, @PathParam("keycol") String keycol,@PathParam("key") String key) {
return metadao.listRow(db, table, keycol, key);
}
@Override
@POST
@Path("{db}/{table}")
@Consumes(MediaType.TEXT_PLAIN)
public void updateRow(@PathParam("db") String db,
@PathParam("table") String table, String rowObject) {
metadao.writeRow(db, table, new JsonObject(rowObject));
// TODO Auto-generated method stub
}
}
| 3,373 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/DaoProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
import java.util.Map;
import org.apache.commons.configuration.AbstractConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.netflix.paas.exceptions.NotFoundException;
/**
* Return an implementation of a DAO by schemaName and type. The schema name makes is possible
* to have separates daos for the same type.
*
* @author elandau
*/
public class DaoProvider {
private static final Logger LOG = LoggerFactory.getLogger(DaoProvider.class);
private static final String DAO_TYPE_FORMAT = "com.netflix.paas.schema.%s.type";
private final Map<String, DaoSchemaProvider> schemaTypes;
private final Map<String, DaoSchema> schemas;
private final AbstractConfiguration configuration;
@Inject
public DaoProvider(Map<String, DaoSchemaProvider> schemaTypes, AbstractConfiguration configuration) {
this.schemaTypes = schemaTypes;
this.schemas = Maps.newHashMap();
this.configuration = configuration;
}
public <T> Dao<T> getDao(String schemaName, Class<T> type) throws NotFoundException {
return getDao(new DaoKey<T>(schemaName, type));
}
public synchronized <T> Dao<T> getDao(DaoKey<T> key) throws NotFoundException {
return getSchema(key.getSchema()).getDao(key.getType());
}
public synchronized DaoSchema getSchema(String schemaName) throws NotFoundException {
DaoSchema schema = schemas.get(schemaName);
if (schema == null) {
String propertyName = String.format(DAO_TYPE_FORMAT, schemaName.toLowerCase());
String daoType = configuration.getString(propertyName);
Preconditions.checkNotNull(daoType, "No DaoType specified for " + schemaName + " (" + propertyName + ")");
DaoSchemaProvider provider = schemaTypes.get(daoType);
if (provider == null) {
LOG.warn("Unable to find DaoManager for schema " + schemaName + "(" + daoType + ")");
throw new NotFoundException(DaoSchemaProvider.class, daoType);
}
schema = provider.getSchema(schemaName);
schemas.put(schemaName, schema);
LOG.info("Created DaoSchema for " + schemaName);
}
return schema;
}
}
| 3,374 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/DaoKey.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
/**
* Unique identified for a DAO and it's entity. The key makes it possible
* to have the same entity class stored in different schemas
*
* @author elandau
*
*/
public class DaoKey<T> implements Comparable<DaoKey>{
private final String schema;
private final Class<T> type;
public DaoKey(String schema, Class<T> type) {
this.schema = schema;
this.type = type;
}
public String getSchema() {
return schema;
}
public Class<T> getType() {
return type;
}
@Override
public int compareTo(DaoKey o) {
int schemaCompare = schema.compareTo(o.schema);
if (schemaCompare != 0)
return schemaCompare;
return this.type.getCanonicalName().compareTo(o.getType().getCanonicalName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((schema == null) ? 0 : schema.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
DaoKey other = (DaoKey) obj;
if (!schema.equals(other.schema))
return false;
if (!type.equals(other.type))
return false;
return true;
}
}
| 3,375 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/DaoManagerType.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
public enum DaoManagerType {
CONFIGURATION,
}
| 3,376 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/DaoSchema.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
import java.util.Collection;
public interface DaoSchema {
/**
* Create the underlying storage for the schema. Does not create the Daos
*/
public void createSchema();
/**
* Delete store for the schema and all child daos
*/
public void dropSchema();
/**
* Get a dao for this type
* @param type
* @return
*/
public <T> Dao<T> getDao(Class<T> type);
/**
* Retrive all Daos managed by this schema
* @return
*/
public Collection<Dao<?>> listDaos();
/**
* Determine if the storage for this schema exists
* @return
*/
public boolean isExists();
}
| 3,377 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/Dao.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
import java.util.Collection;
import javax.persistence.PersistenceException;
/**
* Generic DAO interface
* @author elandau
*
* @param <T>
*/
public interface Dao<T> extends DaoStatus {
/**
* Read a single entity by key
*
* @param key
* @return
*/
public T read(String key) throws PersistenceException;
/**
* Read entities for a set of keys
* @param keys
* @return
* @throws PersistenceException
*/
public Collection<T> read(Collection<String> keys) throws PersistenceException;
/**
* Write a single entity
* @param entity
*/
public void write(T entity) throws PersistenceException;
/**
* List all entities
*
* @return
*
* @todo
*/
public Collection<T> list() throws PersistenceException;
/**
* List all ids without necessarily retrieving all the entities
* @return
* @throws PersistenceException
*/
public Collection<String> listIds() throws PersistenceException;
/**
* Delete a row by key
* @param key
*/
public void delete(String key) throws PersistenceException;
/**
* Create the underlying storage for this dao
* @throws PersistenceException
*/
public void createTable() throws PersistenceException;
/**
* Delete the storage for this dao
* @throws PersistenceException
*/
public void deleteTable() throws PersistenceException;
/**
* Cleanup resources used by this dao as part of the shutdown process
*/
public void shutdown();
}
| 3,378 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/DaoSchemaProvider.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
import java.util.Collection;
import com.netflix.paas.exceptions.NotFoundException;
/**
* Manage all DAOs for an application.
*
* @author elandau
*
*/
public interface DaoSchemaProvider {
/**
* List all schemas for which daos were created
* @return
*/
Collection<DaoSchema> listSchemas();
/**
* Get the schema by name
* @return
* @throws NotFoundException
*/
DaoSchema getSchema(String schema) throws NotFoundException;
}
| 3,379 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/dao/DaoStatus.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.dao;
public interface DaoStatus {
public String getEntityType();
public String getDaoType();
public Boolean healthcheck();
public Boolean isExists();
}
| 3,380 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/provider/TableDataResourceFactory.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.provider;
import com.netflix.paas.entity.TableEntity;
import com.netflix.paas.exceptions.NotFoundException;
import com.netflix.paas.resources.TableDataResource;
/**
* Provides a REST resource that can query the table specified by the entity
*
* @author elandau
*/
public interface TableDataResourceFactory {
TableDataResource getTableDataResource(TableEntity entity) throws NotFoundException;
}
| 3,381 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta/impl/MetaConstants.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.meta.impl;
public interface MetaConstants {
public static final String CASSANDRA_KEYSPACE_ENTITY_TYPE = "com.test.entity.type.cassandra.keyspace";
public static final String PAAS_TABLE_ENTITY_TYPE = "com.test.entity.type.paas.table";
public static final String PAAS_DB_ENTITY_TYPE = "com.test.entity.type.paas.db";
public static final String CASSANDRA_CF_TYPE = "com.test.entity.type.cassandra.columnfamily";
public static final String CASSANDRA_TIMESERIES_TYPE = "com.test.entity.type.cassandra.timeseries";
public static final String PAAS_CLUSTER_ENTITY_TYPE = "com.test.entity.type.paas.table";
public static final String STORAGE_TYPE = "com.test.trait.type.storagetype";
public static final String RESOLUTION_TYPE = "com.test.trait.type.resolutionstring";
public static final String NAME_TYPE = "com.test.trait.type.name";
public static final String RF_TYPE = "com.test.trait.type.replicationfactor";
public static final String STRATEGY_TYPE = "com.test.trait.type.strategy";
public static final String COMPARATOR_TYPE = "com.test.trait.type.comparator";
public static final String KEY_VALIDATION_CLASS_TYPE = "com.test.trait.type.key_validation_class";
public static final String COLUMN_VALIDATION_CLASS_TYPE = "com.test.trait.type.validation_class";
public static final String DEFAULT_VALIDATION_CLASS_TYPE = "com.test.trait.type.default_validation_class";
public static final String COLUMN_NAME_TYPE = "com.test.trait.type.colum_name";
public static final String CONTAINS_TYPE = "com.test.relation.type.contains";
}
| 3,382 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta/entity/PaasDBEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.meta.entity;
import com.netflix.paas.json.JsonObject;
import com.netflix.paas.meta.impl.MetaConstants;
import com.netflix.paas.util.Pair;
public class PaasDBEntity extends Entity{
public static class Builder {
private PaasDBEntity entity = new PaasDBEntity();
public Builder withJsonPayLoad(JsonObject payLoad) {
entity.setRowKey(MetaConstants.PAAS_DB_ENTITY_TYPE);
String payLoadName = payLoad.getString("name");
String load = payLoad.toString();
entity.setName(payLoadName);
entity.setPayLoad(load);
// Pair<String, String> p = new Pair<String, String>(payLoadName, load);
// entity.addColumn(p);
return this;
}
public PaasDBEntity build() {
return entity;
}
}
public static Builder builder() {
return new Builder();
}
}
| 3,383 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta/entity/PaasTableEntity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.meta.entity;
import java.util.ArrayList;
import java.util.List;
import com.netflix.paas.json.JsonObject;
import com.netflix.paas.meta.impl.MetaConstants;
import com.netflix.paas.util.Pair;
public class PaasTableEntity extends Entity{
private String schemaName;
private List<Pair<String, String>> columns = new ArrayList<Pair<String, String>>();
private String primarykey;
public static class Builder {
private PaasTableEntity entity = new PaasTableEntity();
public Builder withJsonPayLoad(JsonObject payLoad, String schemaName) {
entity.setRowKey(MetaConstants.PAAS_TABLE_ENTITY_TYPE);
entity.setSchemaName(schemaName);
String payLoadName = payLoad.getString("name");
String load = payLoad.toString();
entity.setName(payLoadName);
String columnswithtypes = payLoad.getString("columns");
String[] allCols = columnswithtypes.split(",");
for (String col:allCols) {
String type;
String name;
if (!col.contains(":")) {
type="text";
name=col;
}
else {
name = col.split(":")[0];
type = col.split(":")[1];
}
Pair<String, String> p = new Pair<String, String>(type, name);
entity.addColumn(p);
}
entity.setPrimarykey(payLoad.getString("primarykey"));
entity.setPayLoad(load);
return this;
}
public PaasTableEntity build() {
return entity;
}
}
public static Builder builder() {
return new Builder();
}
public String getSchemaName() {
return schemaName;
}
private void setSchemaName(String schemaname) {
this.schemaName = schemaname;
}
private void addColumn(Pair<String, String> pair) {
columns.add(pair);
}
public List<Pair<String,String>> getColumns() {
return columns;
}
public String getPrimarykey() {
return primarykey;
}
private void setPrimarykey(String primarykey) {
this.primarykey = primarykey;
}
}
| 3,384 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta/entity/Entity.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.meta.entity;
import java.util.ArrayList;
import java.util.List;
import com.netflix.paas.util.Pair;
public class Entity {
protected String rowKey;
protected String name;
protected String payLoad;
public String getRowKey() {
return rowKey;
}
public String getName() {
return name;
}
protected void setRowKey(String rowkey) {
this.rowKey = rowkey;
}
protected void setName(String name) {
this.name = name;
}
public String getPayLoad() {
return payLoad;
}
protected void setPayLoad(String payLoad) {
this.payLoad = payLoad;
}
}
| 3,385 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/meta/dao/MetaDao.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.meta.dao;
import com.netflix.paas.json.JsonObject;
import com.netflix.paas.meta.entity.Entity;
public interface MetaDao {
public void writeMetaEntity(Entity entity);
public Entity readMetaEntity(String rowKey);
public void writeRow(String db, String table, JsonObject rowObj);
public String listRow(String db, String table, String keycol, String key);
}
| 3,386 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/exceptions/AlreadyExistsException.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.exceptions;
public class AlreadyExistsException extends Exception {
private static final long serialVersionUID = 5796840344994375807L;
private final String type;
private final String id;
public AlreadyExistsException(String type, String id) {
super("%s:%s already exists".format(type, id));
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public String getId() {
return id;
}
}
| 3,387 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/exceptions/InvalidConfException.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.exceptions;
public class InvalidConfException extends Exception{
private static final long serialVersionUID = 1L;
public InvalidConfException() {
super();
}
public InvalidConfException(String message) {
super(message);
}
}
| 3,388 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/exceptions/PaasException.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.exceptions;
public class PaasException extends Exception {
public PaasException(String message, Exception e) {
super(message, e);
}
}
| 3,389 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/exceptions/NotFoundException.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.exceptions;
import javax.persistence.PersistenceException;
public class NotFoundException extends PersistenceException {
private static final long serialVersionUID = 1320561942271503959L;
private final String type;
private final String id;
public NotFoundException(Class<?> clazz, String id) {
this(clazz.getName(), id);
}
public NotFoundException(String type, String id) {
super(String.format("Cannot find %s:%s", type, id));
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public String getId() {
return id;
}
}
| 3,390 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/JsonArray.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json;
import java.util.*;
import com.netflix.paas.json.impl.Base64;
import com.netflix.paas.json.impl.Json;
/**
* Represents a JSON array
*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class JsonArray extends JsonElement implements Iterable<Object> {
final List<Object> list;
public JsonArray(List<Object> array) {
this.list = array;
}
public JsonArray(Object[] array) {
this.list = Arrays.asList(array);
}
public JsonArray() {
this.list = new ArrayList<Object>();
}
public JsonArray(String jsonString) {
list = Json.decodeValue(jsonString, List.class);
}
public JsonArray addString(String str) {
list.add(str);
return this;
}
public JsonArray addObject(JsonObject value) {
list.add(value.map);
return this;
}
public JsonArray addArray(JsonArray value) {
list.add(value.list);
return this;
}
public JsonArray addElement(JsonElement value) {
if (value.isArray()) {
return addArray(value.asArray());
}
return addObject(value.asObject());
}
public JsonArray addNumber(Number value) {
list.add(value);
return this;
}
public JsonArray addBoolean(Boolean value) {
list.add(value);
return this;
}
public JsonArray addBinary(byte[] value) {
String encoded = Base64.encodeBytes(value);
list.add(encoded);
return this;
}
public JsonArray add(Object obj) {
if (obj instanceof JsonObject) {
obj = ((JsonObject) obj).map;
} else if (obj instanceof JsonArray) {
obj = ((JsonArray) obj).list;
}
list.add(obj);
return this;
}
public int size() {
return list.size();
}
public <T> T get(final int index) {
return convertObject(list.get(index));
}
@Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
Iterator<Object> iter = list.iterator();
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public Object next() {
return convertObject(iter.next());
}
@Override
public void remove() {
iter.remove();
}
};
}
public boolean contains(Object value) {
return list.contains(value);
}
public String encode() throws EncodeException {
return Json.encode(this.list);
}
public JsonArray copy() {
return new JsonArray(encode());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
JsonArray that = (JsonArray) o;
if (this.list.size() != that.list.size())
return false;
Iterator<?> iter = that.list.iterator();
for (Object entry : this.list) {
Object other = iter.next();
if (!entry.equals(other)) {
return false;
}
}
return true;
}
public Object[] toArray() {
return convertList(list).toArray();
}
@SuppressWarnings("unchecked")
static List<Object> convertList(List<?> list) {
List<Object> arr = new ArrayList<Object>(list.size());
for (Object obj : list) {
if (obj instanceof Map) {
arr.add(JsonObject.convertMap((Map<String, Object>) obj));
} else if (obj instanceof JsonObject) {
arr.add(((JsonObject) obj).toMap());
} else if (obj instanceof List) {
arr.add(convertList((List<?>) obj));
} else {
arr.add(obj);
}
}
return arr;
}
@SuppressWarnings("unchecked")
private static <T> T convertObject(final Object obj) {
Object retVal = obj;
if (obj != null) {
if (obj instanceof List) {
retVal = new JsonArray((List<Object>) obj);
} else if (obj instanceof Map) {
retVal = new JsonObject((Map<String, Object>) obj);
}
}
return (T)retVal;
}
}
| 3,391 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/JsonElement.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json;
public abstract class JsonElement {
public boolean isArray() {
return this instanceof JsonArray;
}
public boolean isObject() {
return this instanceof JsonObject;
}
public JsonArray asArray() {
return (JsonArray) this;
}
public JsonObject asObject() {
return (JsonObject) this;
}
}
| 3,392 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/JsonObject.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.netflix.paas.json.impl.Base64;
import com.netflix.paas.json.impl.Json;
/**
*
* Represents a JSON object
*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class JsonObject extends JsonElement {
final Map<String, Object> map;
/**
* Create a JSON object based on the specified Map
*
* @param map
*/
public JsonObject(Map<String, Object> map) {
this.map = map;
}
/**
* Create an empty JSON object
*/
public JsonObject() {
this.map = new LinkedHashMap<String, Object>();
}
/**
* Create a JSON object from a string form of a JSON object
*
* @param jsonString
* The string form of a JSON object
*/
public JsonObject(String jsonString) {
map = Json.decodeValue(jsonString, Map.class);
}
public JsonObject putString(String fieldName, String value) {
map.put(fieldName, value);
return this;
}
public JsonObject putObject(String fieldName, JsonObject value) {
map.put(fieldName, value == null ? null : value.map);
return this;
}
public JsonObject putArray(String fieldName, JsonArray value) {
map.put(fieldName, value.list);
return this;
}
public JsonObject putElement(String fieldName, JsonElement value) {
if(value.isArray()){
return this.putArray(fieldName, value.asArray());
}
return this.putObject(fieldName, value.asObject());
}
public JsonObject putNumber(String fieldName, Number value) {
map.put(fieldName, value);
return this;
}
public JsonObject putBoolean(String fieldName, Boolean value) {
map.put(fieldName, value);
return this;
}
public JsonObject putBinary(String fieldName, byte[] binary) {
map.put(fieldName, Base64.encodeBytes(binary));
return this;
}
public JsonObject putValue(String fieldName, Object value) {
if (value instanceof JsonObject) {
putObject(fieldName, (JsonObject)value);
} else if (value instanceof JsonArray) {
putArray(fieldName, (JsonArray)value);
} else {
map.put(fieldName, value);
}
return this;
}
public String getString(String fieldName) {
return (String) map.get(fieldName);
}
@SuppressWarnings("unchecked")
public JsonObject getObject(String fieldName) {
Map<String, Object> m = (Map<String, Object>) map.get(fieldName);
return m == null ? null : new JsonObject(m);
}
@SuppressWarnings("unchecked")
public JsonArray getArray(String fieldName) {
List<Object> l = (List<Object>) map.get(fieldName);
return l == null ? null : new JsonArray(l);
}
public JsonElement getElement(String fieldName) {
Object element = map.get(fieldName);
if (element instanceof Map<?,?>){
return getObject(fieldName);
}
if (element instanceof List<?>){
return getArray(fieldName);
}
throw new ClassCastException();
}
public Number getNumber(String fieldName) {
return (Number) map.get(fieldName);
}
public Long getLong(String fieldName) {
Number num = (Number) map.get(fieldName);
return num == null ? null : num.longValue();
}
public Integer getInteger(String fieldName) {
Number num = (Number) map.get(fieldName);
return num == null ? null : num.intValue();
}
public Boolean getBoolean(String fieldName) {
return (Boolean) map.get(fieldName);
}
public byte[] getBinary(String fieldName) {
String encoded = (String) map.get(fieldName);
return Base64.decode(encoded);
}
public String getString(String fieldName, String def) {
String str = getString(fieldName);
return str == null ? def : str;
}
public JsonObject getObject(String fieldName, JsonObject def) {
JsonObject obj = getObject(fieldName);
return obj == null ? def : obj;
}
public JsonArray getArray(String fieldName, JsonArray def) {
JsonArray arr = getArray(fieldName);
return arr == null ? def : arr;
}
public JsonElement getElement(String fieldName, JsonElement def) {
JsonElement elem = getElement(fieldName);
return elem == null ? def : elem;
}
public boolean getBoolean(String fieldName, boolean def) {
Boolean b = getBoolean(fieldName);
return b == null ? def : b;
}
public Number getNumber(String fieldName, int def) {
Number n = getNumber(fieldName);
return n == null ? def : n;
}
public Long getLong(String fieldName, long def) {
Number num = (Number) map.get(fieldName);
return num == null ? def : num.longValue();
}
public Integer getInteger(String fieldName, int def) {
Number num = (Number) map.get(fieldName);
return num == null ? def : num.intValue();
}
public byte[] getBinary(String fieldName, byte[] def) {
byte[] b = getBinary(fieldName);
return b == null ? def : b;
}
public Set<String> getFieldNames() {
return map.keySet();
}
@SuppressWarnings("unchecked")
public <T> T getValue(String fieldName) {
Object obj = map.get(fieldName);
if (obj != null) {
if (obj instanceof Map) {
obj = new JsonObject((Map)obj);
} else if (obj instanceof List) {
obj = new JsonArray((List)obj);
}
}
return (T)obj;
}
@SuppressWarnings("unchecked")
public <T> T getField(String fieldName) {
Object obj = map.get(fieldName);
if (obj instanceof Map) {
obj = new JsonObject((Map)obj);
} else if (obj instanceof List) {
obj = new JsonArray((List)obj);
}
return (T)obj;
}
public Object removeField(String fieldName) {
return map.remove(fieldName) != null;
}
public int size() {
return map.size();
}
public JsonObject mergeIn(JsonObject other) {
map.putAll(other.map);
return this;
}
public String encode() {
return Json.encode(this.map);
}
public JsonObject copy() {
return new JsonObject(encode());
}
@Override
public String toString() {
return encode();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
JsonObject that = (JsonObject) o;
if (this.map.size() != that.map.size())
return false;
for (Map.Entry<String, Object> entry : this.map.entrySet()) {
Object val = entry.getValue();
if (val == null) {
if (that.map.get(entry.getKey()) != null) {
return false;
}
} else {
if (!entry.getValue().equals(that.map.get(entry.getKey()))) {
return false;
}
}
}
return true;
}
public Map<String, Object> toMap() {
return convertMap(map);
}
@SuppressWarnings("unchecked")
static Map<String, Object> convertMap(Map<String, Object> map) {
Map<String, Object> converted = new LinkedHashMap<String, Object>(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object obj = entry.getValue();
if (obj instanceof Map) {
Map<String, Object> jm = (Map<String, Object>) obj;
converted.put(entry.getKey(), convertMap(jm));
} else if (obj instanceof List) {
List<Object> list = (List<Object>) obj;
converted.put(entry.getKey(), JsonArray.convertList(list));
} else {
converted.put(entry.getKey(), obj);
}
}
return converted;
}
}
| 3,393 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/EncodeException.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class EncodeException extends RuntimeException {
public EncodeException(String message) {
super(message);
}
public EncodeException() {
}
}
| 3,394 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/DecodeException.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class DecodeException extends RuntimeException {
public DecodeException() {
}
public DecodeException(String message) {
super(message);
}
}
| 3,395 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/impl/Base64.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json.impl;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
* <p/>
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
* several pieces of information to the encoder. In the "higher level" methods such as
* encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds
* (though that breaks strict Base64 compatibility), and encoding using the URL-safe
* and Ordered dialects.</p>
* <p/>
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
* <p/>
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DONT_BREAK_LINES );</code>
* <p/>
* <p>to compress the data before encoding it and then making the output have no newline characters.</p>
* <p/>
* <p/>
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.2.2 - Fixed encodeFileToFile and decodeFileToFile to use the
* Base64.InputStream class to encode and decode on the fly which uses
* less memory than encoding/decoding an entire file into memory before writing.</li>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
* <p/>
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
* <p/>
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author [email protected]
* @version 2.2.2
*/
public class Base64 {
/* ******** P U B L I C F I E L D S ******** */
/**
* No options specified. Value is zero.
*/
public final static int NO_OPTIONS = 0;
/**
* Specify encoding.
*/
public final static int ENCODE = 1;
/**
* Specify decoding.
*/
public final static int DECODE = 0;
/**
* Specify that data should be gzip-compressed.
*/
public final static int GZIP = 2;
/**
* Don't break lines when encoding (violates strict Base64 specification)
*/
public final static int DONT_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/* ******** P R I V A T E F I E L D S ******** */
/**
* Maximum line length (76) of Base64 output.
*/
private final static int MAX_LINE_LENGTH = 76;
/**
* The equals sign (=) as a byte.
*/
private final static byte EQUALS_SIGN = (byte) '=';
/**
* The new line character (\n) as a byte.
*/
private final static byte NEW_LINE = (byte) '\n';
/**
* Preferred encoding.
*/
private final static String PREFERRED_ENCODING = "UTF-8";
// I think I end up not using the BAD_ENCODING indicator.
// private final static byte BAD_ENCODING = -9; // Indicates error in encoding
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/**
* The 64 valid Base64 values.
*/
// private final static byte[] ALPHABET;
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {(byte) 'A',
(byte) 'B',
(byte) 'C',
(byte) 'D',
(byte) 'E',
(byte) 'F',
(byte) 'G',
(byte) 'H',
(byte) 'I',
(byte) 'J',
(byte) 'K',
(byte) 'L',
(byte) 'M',
(byte) 'N',
(byte) 'O',
(byte) 'P',
(byte) 'Q',
(byte) 'R',
(byte) 'S',
(byte) 'T',
(byte) 'U',
(byte) 'V',
(byte) 'W',
(byte) 'X',
(byte) 'Y',
(byte) 'Z',
(byte) 'a',
(byte) 'b',
(byte) 'c',
(byte) 'd',
(byte) 'e',
(byte) 'f',
(byte) 'g',
(byte) 'h',
(byte) 'i',
(byte) 'j',
(byte) 'k',
(byte) 'l',
(byte) 'm',
(byte) 'n',
(byte) 'o',
(byte) 'p',
(byte) 'q',
(byte) 'r',
(byte) 's',
(byte) 't',
(byte) 'u',
(byte) 'v',
(byte) 'w',
(byte) 'x',
(byte) 'y',
(byte) 'z',
(byte) '0',
(byte) '1',
(byte) '2',
(byte) '3',
(byte) '4',
(byte) '5',
(byte) '6',
(byte) '7',
(byte) '8',
(byte) '9',
(byte) '+',
(byte) '/'};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
*/
private final static byte[] _STANDARD_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5,
-5, // Whitespace: Tab and Linefeed
-9,
-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 14 - 26
-9,
-9,
-9,
-9,
-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,
-9,
-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,
53,
54,
55,
56,
57,
58,
59,
60,
61, // Numbers zero through nine
-9,
-9,
-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,
-9,
-9, // Decimal 62 - 64
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13, // Letters 'A' through 'N'
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25, // Letters 'O' through 'Z'
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 91 - 96
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38, // Letters 'a' through 'm'
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51, // Letters 'n' through 'z'
-9,
-9,
-9,
-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {(byte) 'A',
(byte) 'B',
(byte) 'C',
(byte) 'D',
(byte) 'E',
(byte) 'F',
(byte) 'G',
(byte) 'H',
(byte) 'I',
(byte) 'J',
(byte) 'K',
(byte) 'L',
(byte) 'M',
(byte) 'N',
(byte) 'O',
(byte) 'P',
(byte) 'Q',
(byte) 'R',
(byte) 'S',
(byte) 'T',
(byte) 'U',
(byte) 'V',
(byte) 'W',
(byte) 'X',
(byte) 'Y',
(byte) 'Z',
(byte) 'a',
(byte) 'b',
(byte) 'c',
(byte) 'd',
(byte) 'e',
(byte) 'f',
(byte) 'g',
(byte) 'h',
(byte) 'i',
(byte) 'j',
(byte) 'k',
(byte) 'l',
(byte) 'm',
(byte) 'n',
(byte) 'o',
(byte) 'p',
(byte) 'q',
(byte) 'r',
(byte) 's',
(byte) 't',
(byte) 'u',
(byte) 'v',
(byte) 'w',
(byte) 'x',
(byte) 'y',
(byte) 'z',
(byte) '0',
(byte) '1',
(byte) '2',
(byte) '3',
(byte) '4',
(byte) '5',
(byte) '6',
(byte) '7',
(byte) '8',
(byte) '9',
(byte) '-',
(byte) '_'};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5,
-5, // Whitespace: Tab and Linefeed
-9,
-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 14 - 26
-9,
-9,
-9,
-9,
-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,
53,
54,
55,
56,
57,
58,
59,
60,
61, // Numbers zero through nine
-9,
-9,
-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,
-9,
-9, // Decimal 62 - 64
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13, // Letters 'A' through 'N'
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25, // Letters 'O' through 'Z'
-9,
-9,
-9,
-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38, // Letters 'a' through 'm'
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51, // Letters 'n' through 'z'
-9,
-9,
-9,
-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {(byte) '-',
(byte) '0',
(byte) '1',
(byte) '2',
(byte) '3',
(byte) '4',
(byte) '5',
(byte) '6',
(byte) '7',
(byte) '8',
(byte) '9',
(byte) 'A',
(byte) 'B',
(byte) 'C',
(byte) 'D',
(byte) 'E',
(byte) 'F',
(byte) 'G',
(byte) 'H',
(byte) 'I',
(byte) 'J',
(byte) 'K',
(byte) 'L',
(byte) 'M',
(byte) 'N',
(byte) 'O',
(byte) 'P',
(byte) 'Q',
(byte) 'R',
(byte) 'S',
(byte) 'T',
(byte) 'U',
(byte) 'V',
(byte) 'W',
(byte) 'X',
(byte) 'Y',
(byte) 'Z',
(byte) '_',
(byte) 'a',
(byte) 'b',
(byte) 'c',
(byte) 'd',
(byte) 'e',
(byte) 'f',
(byte) 'g',
(byte) 'h',
(byte) 'i',
(byte) 'j',
(byte) 'k',
(byte) 'l',
(byte) 'm',
(byte) 'n',
(byte) 'o',
(byte) 'p',
(byte) 'q',
(byte) 'r',
(byte) 's',
(byte) 't',
(byte) 'u',
(byte) 'v',
(byte) 'w',
(byte) 'x',
(byte) 'y',
(byte) 'z'};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5,
-5, // Whitespace: Tab and Linefeed
-9,
-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 14 - 26
-9,
-9,
-9,
-9,
-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,
2,
3,
4,
5,
6,
7,
8,
9,
10, // Numbers zero through nine
-9,
-9,
-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,
-9,
-9, // Decimal 62 - 64
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23, // Letters 'A' through 'M'
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36, // Letters 'N' through 'Z'
-9,
-9,
-9,
-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50, // Letters 'a' through 'm'
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63, // Letters 'n' through 'z'
-9,
-9,
-9,
-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet(final int options) {
if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) {
return Base64._URL_SAFE_ALPHABET;
} else if ((options & Base64.ORDERED) == Base64.ORDERED) {
return Base64._ORDERED_ALPHABET;
} else {
return Base64._STANDARD_ALPHABET;
}
} // end getAlphabet
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet(final int options) {
if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) {
return Base64._URL_SAFE_DECODABET;
} else if ((options & Base64.ORDERED) == Base64.ORDERED) {
return Base64._ORDERED_DECODABET;
} else {
return Base64._STANDARD_DECODABET;
}
} // end getAlphabet
/**
* Defeats instantiation.
*/
private Base64() {
}
/**
* Encodes or decodes two files from the command line;
* <strong>feel free to delete this method (in fact you probably should)
* if you're embedding this code into a larger program.</strong>
*/
public final static void main(final String[] args) {
if (args.length < 3) {
Base64.usage("Not enough arguments.");
} // end if: args.length < 3
else {
String flag = args[0];
String infile = args[1];
String outfile = args[2];
if (flag.equals("-e")) {
Base64.encodeFileToFile(infile, outfile);
} // end if: encode
else if (flag.equals("-d")) {
Base64.decodeFileToFile(infile, outfile);
} // end else if: decode
else {
Base64.usage("Unknown flag: " + flag);
} // end else
} // end else
} // end main
/**
* Prints command line usage.
*
* @param msg A message to include with usage info.
*/
private final static void usage(final String msg) {
System.err.println(msg);
System.err.println("Usage: java Base64 -e|-d inputfile outputfile");
} // end usage
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4(final byte[] b4, final byte[] threeBytes, final int numSigBytes, final int options) {
Base64.encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);
return b4;
} // end encode3to4
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(final byte[] source,
final int srcOffset,
final int numSigBytes,
final byte[] destination,
final int destOffset,
final int options) {
byte[] ALPHABET = Base64.getAlphabet(options);
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = (numSigBytes > 0 ? source[srcOffset] << 24 >>> 8 : 0) | (numSigBytes > 1 ? source[srcOffset + 1] << 24 >>> 16
: 0) |
(numSigBytes > 2 ? source[srcOffset + 2] << 24 >>> 24 : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f];
destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 0x3f];
destination[destOffset + 3] = ALPHABET[inBuff & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f];
destination[destOffset + 2] = ALPHABET[inBuff >>> 6 & 0x3f];
destination[destOffset + 3] = Base64.EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[inBuff >>> 12 & 0x3f];
destination[destOffset + 2] = Base64.EQUALS_SIGN;
destination[destOffset + 3] = Base64.EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @since 1.4
*/
public static String encodeObject(final java.io.Serializable serializableObject) {
return Base64.encodeObject(serializableObject, Base64.NO_OPTIONS);
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* <p/>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p/>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p/>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeObject(final java.io.Serializable serializableObject, final int options) {
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.io.ObjectOutputStream oos = null;
java.util.zip.GZIPOutputStream gzos = null;
// Isolate options
int gzip = options & Base64.GZIP;
int dontBreakLines = options & Base64.DONT_BREAK_LINES;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream(baos, Base64.ENCODE | options);
// GZip?
if (gzip == Base64.GZIP) {
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream(gzos);
} // end if: gzip
else {
oos = new java.io.ObjectOutputStream(b64os);
}
oos.writeObject(serializableObject);
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
return null;
} // end catch
finally {
try {
oos.close();
} catch (Exception e) {
}
try {
gzos.close();
} catch (Exception e) {
}
try {
b64os.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
} // end finally
// Return value according to relevant encoding.
try {
return new String(baos.toByteArray(), Base64.PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String(baos.toByteArray());
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @since 1.4
*/
public static String encodeBytes(final byte[] source) {
return Base64.encodeBytes(source, 0, source.length, Base64.NO_OPTIONS);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p/>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p/>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p/>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
* @param source The data to convert
* @param options Specified options
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes(final byte[] source, final int options) {
return Base64.encodeBytes(source, 0, source.length, options);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @since 1.4
*/
public static String encodeBytes(final byte[] source, final int off, final int len) {
return Base64.encodeBytes(source, off, len, Base64.NO_OPTIONS);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p/>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p/>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p/>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options options alphabet type is pulled from this (standard, url-safe, ordered)
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes(final byte[] source, final int off, final int len, final int options) {
// Isolate options
int dontBreakLines = options & Base64.DONT_BREAK_LINES;
int gzip = options & Base64.GZIP;
// Compress?
if (gzip == Base64.GZIP) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream(baos, Base64.ENCODE | options);
gzos = new java.util.zip.GZIPOutputStream(b64os);
gzos.write(source, off, len);
gzos.close();
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
return null;
} // end catch
finally {
try {
gzos.close();
} catch (Exception e) {
}
try {
b64os.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
} // end finally
// Return value according to relevant encoding.
try {
return new String(baos.toByteArray(), Base64.PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String(baos.toByteArray());
} // end catch
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
// Convert option to boolean in way that code likes it.
boolean breakLines = dontBreakLines == 0;
int len43 = len * 4 / 3;
byte[] outBuff = new byte[len43 + (len % 3 > 0 ? 4 : 0) // Account for padding
+
(breakLines ? len43 / Base64.MAX_LINE_LENGTH : 0)]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
Base64.encode3to4(source, d + off, 3, outBuff, e, options);
lineLength += 4;
if (breakLines && lineLength == Base64.MAX_LINE_LENGTH) {
outBuff[e + 4] = Base64.NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if (d < len) {
Base64.encode3to4(source, d + off, len - d, outBuff, e, options);
e += 4;
} // end if: some padding needed
// Return value according to relevant encoding.
try {
return new String(outBuff, 0, e, Base64.PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String(outBuff, 0, e);
} // end catch
} // end else: don't compress
} // end encodeBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3(final byte[] source,
final int srcOffset,
final byte[] destination,
final int destOffset,
final int options) {
byte[] DECODABET = Base64.getDecodabet(options);
// Example: Dk==
if (source[srcOffset + 2] == Base64.EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12;
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL=
else if (source[srcOffset + 3] == Base64.EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12 |
(DECODABET[source[srcOffset + 2]] & 0xFF) << 6;
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
else {
try {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = (DECODABET[source[srcOffset]] & 0xFF) << 18 | (DECODABET[source[srcOffset + 1]] & 0xFF) << 12 |
(DECODABET[source[srcOffset + 2]] & 0xFF) << 6 |
DECODABET[source[srcOffset + 3]] &
0xFF;
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) outBuff;
return 3;
} catch (Exception e) {
System.out.println("" + source[srcOffset] + ": " + DECODABET[source[srcOffset]]);
System.out.println("" + source[srcOffset + 1] + ": " + DECODABET[source[srcOffset + 1]]);
System.out.println("" + source[srcOffset + 2] + ": " + DECODABET[source[srcOffset + 2]]);
System.out.println("" + source[srcOffset + 3] + ": " + DECODABET[source[srcOffset + 3]]);
return -1;
} // end catch
}
} // end decodeToBytes
/**
* Very low-level access to decoding ASCII characters in
* the form of a byte array. Does not support automatically
* gunzipping or any other "fancy" features.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @return decoded data
* @since 1.3
*/
public static byte[] decode(final byte[] source, final int off, final int len, final int options) {
byte[] DECODABET = Base64.getDecodabet(options);
int len34 = len * 3 / 4;
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for (i = off; i < off + len; i++) {
sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= Base64.WHITE_SPACE_ENC) // White space, Equals sign or better
{
if (sbiDecode >= Base64.EQUALS_SIGN_ENC) {
b4[b4Posn++] = sbiCrop;
if (b4Posn > 3) {
outBuffPosn += Base64.decode4to3(b4, 0, outBuff, outBuffPosn, options);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (sbiCrop == Base64.EQUALS_SIGN) {
break;
}
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)");
return null;
} // end else:
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @since 1.4
*/
public static byte[] decode(final String s) {
return Base64.decode(s, Base64.NO_OPTIONS);
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @since 1.4
*/
public static byte[] decode(final String s, final int options) {
byte[] bytes;
try {
bytes = s.getBytes(Base64.PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uee) {
bytes = s.getBytes();
} // end catch
// </change>
// Decode
bytes = Base64.decode(bytes, 0, bytes.length, options);
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
if (bytes != null && bytes.length >= 4) {
int head = bytes[0] & 0xff | bytes[1] << 8 & 0xff00;
if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream(bytes);
gzis = new java.util.zip.GZIPInputStream(bais);
while ((length = gzis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch (java.io.IOException e) {
// Just return originally-decoded bytes
} // end catch
finally {
try {
baos.close();
} catch (Exception e) {
}
try {
gzis.close();
} catch (Exception e) {
}
try {
bais.close();
} catch (Exception e) {
}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @since 1.5
*/
public static Object decodeToObject(final String encodedObject) {
// Decode and gunzip if necessary
byte[] objBytes = Base64.decode(encodedObject);
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream(objBytes);
ois = new java.io.ObjectInputStream(bais);
obj = ois.readObject();
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
obj = null;
} // end catch
catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
obj = null;
} // end catch
finally {
try {
bais.close();
} catch (Exception e) {
}
try {
ois.close();
} catch (Exception e) {
}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @since 2.1
*/
public static boolean encodeToFile(final byte[] dataToEncode, final String filename) {
boolean success = false;
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE);
bos.write(dataToEncode);
success = true;
} // end try
catch (java.io.IOException e) {
success = false;
} // end catch: IOException
finally {
try {
bos.close();
} catch (Exception e) {
}
} // end finally
return success;
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @since 2.1
*/
public static boolean decodeToFile(final String dataToDecode, final String filename) {
boolean success = false;
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.DECODE);
bos.write(dataToDecode.getBytes(Base64.PREFERRED_ENCODING));
success = true;
} // end try
catch (java.io.IOException e) {
success = false;
} // end catch: IOException
finally {
try {
bos.close();
} catch (Exception e) {
}
} // end finally
return success;
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* @param filename Filename for reading encoded data
* @return decoded byte array or null if unsuccessful
* @since 2.1
*/
public static byte[] decodeFromFile(final String filename) {
byte[] decodedData = null;
Base64.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if (file.length() > Integer.MAX_VALUE) {
System.err.println("File is too big for this convenience method (" + file.length() + " bytes).");
return null;
} // end if: file too big for int index
buffer = new byte[(int) file.length()];
// Open a stream
bis = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base64.DECODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
}
// Save in a variable to return
decodedData = new byte[length];
System.arraycopy(buffer, 0, decodedData, 0, length);
} // end try
catch (java.io.IOException e) {
System.err.println("Error decoding from file " + filename);
} // end catch: IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* @param filename Filename for reading binary data
* @return base64-encoded string or null if unsuccessful
* @since 2.1
*/
public static String encodeFromFile(final String filename) {
String encodedData = null;
Base64.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; // Need max() for math on small files
// (v2.2.1)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base64.ENCODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
}
// Save in a variable to return
encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING);
} // end try
catch (java.io.IOException e) {
System.err.println("Error encoding from file " + filename);
} // end catch: IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @return true if the operation is successful
* @since 2.2
*/
public static boolean encodeFileToFile(final String infile, final String outfile) {
boolean success = false;
java.io.InputStream in = null;
java.io.OutputStream out = null;
try {
in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)),
Base64.ENCODE);
out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
byte[] buffer = new byte[65536]; // 64K
int read = -1;
while ((read = in.read(buffer)) >= 0) {
out.write(buffer, 0, read);
} // end while: through file
success = true;
} catch (java.io.IOException exc) {
exc.printStackTrace();
} finally {
try {
in.close();
} catch (Exception exc) {
}
try {
out.close();
} catch (Exception exc) {
}
} // end finally
return success;
} // end encodeFileToFile
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @return true if the operation is successful
* @since 2.2
*/
public static boolean decodeFileToFile(final String infile, final String outfile) {
boolean success = false;
java.io.InputStream in = null;
java.io.OutputStream out = null;
try {
in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)),
Base64.DECODE);
out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
byte[] buffer = new byte[65536]; // 64K
int read = -1;
while ((read = in.read(buffer)) >= 0) {
out.write(buffer, 0, read);
} // end while: through file
success = true;
} catch (java.io.IOException exc) {
exc.printStackTrace();
} finally {
try {
in.close();
} catch (Exception exc) {
}
try {
out.close();
} catch (Exception exc) {
}
} // end finally
return success;
} // end decodeFileToFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private final boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private final byte[] buffer; // Small buffer holding converted data
private final int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private final boolean breakLines; // Break lines at less than 80 characters
private final int options; // Record options used to create the stream.
private final byte[] alphabet; // Local copies to avoid extra method calls
private final byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream(final java.io.InputStream in) {
this(in, Base64.DECODE);
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p/>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p/>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public InputStream(final java.io.InputStream in, final int options) {
super(in);
breakLines = (options & Base64.DONT_BREAK_LINES) != Base64.DONT_BREAK_LINES;
encode = (options & Base64.ENCODE) == Base64.ENCODE;
bufferLength = encode ? 4 : 3;
buffer = new byte[bufferLength];
position = -1;
lineLength = 0;
this.options = options; // Record for later, mostly to determine which alphabet to use
alphabet = Base64.getAlphabet(options);
decodabet = Base64.getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if (position < 0) {
if (encode) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for (int i = 0; i < 3; i++) {
try {
int b = in.read();
// If end of stream, b is -1.
if (b >= 0) {
b3[i] = (byte) b;
numBinaryBytes++;
} // end if: not end of stream
} // end try: read
catch (java.io.IOException e) {
// Only a problem if we got no data at all.
if (i == 0) {
throw e;
}
} // end catch
} // end for: each needed input byte
if (numBinaryBytes > 0) {
Base64.encode3to4(b3, 0, numBinaryBytes, buffer, 0, options);
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1;
}
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for (i = 0; i < 4; i++) {
// Read four "meaningful" bytes:
int b = 0;
do {
b = in.read();
}
while (b >= 0 && decodabet[b & 0x7f] <= Base64.WHITE_SPACE_ENC);
if (b < 0) {
break; // Reads a -1 if end of stream
}
b4[i] = (byte) b;
} // end for: each needed input byte
if (i == 4) {
numSigBytes = Base64.decode4to3(b4, 0, buffer, 0, options);
position = 0;
} // end if: got four characters
else if (i == 0) {
return -1;
} else {
// Must have broken out from above.
throw new java.io.IOException("Improperly padded Base64 input.");
}
} // end else: decode
} // end else: get data
// Got data?
if (position >= 0) {
// End of relevant data?
if ( /*!encode &&*/position >= numSigBytes) {
return -1;
}
if (encode && breakLines && lineLength >= Base64.MAX_LINE_LENGTH) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[position++];
if (position >= bufferLength) {
position = -1;
}
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
else {
// When JDK1.4 is more accepted, use an assertion here.
throw new java.io.IOException("Error in Base64 code reading stream.");
}
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read(final byte[] dest, final int off, final int len) throws java.io.IOException {
int i;
int b;
for (i = 0; i < len; i++) {
b = read();
// if( b < 0 && i == 0 )
// return -1;
if (b >= 0) {
dest[off + i] = (byte) b;
} else if (i == 0) {
return -1;
} else {
break; // Out of 'for' loop
}
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private final boolean encode;
private int position;
private byte[] buffer;
private final int bufferLength;
private int lineLength;
private final boolean breakLines;
private final byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private final int options; // Record for later
private final byte[] alphabet; // Local copies to avoid extra method calls
private final byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream(final java.io.OutputStream out) {
this(out, Base64.ENCODE);
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p/>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p/>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 1.3
*/
public OutputStream(final java.io.OutputStream out, final int options) {
super(out);
breakLines = (options & Base64.DONT_BREAK_LINES) != Base64.DONT_BREAK_LINES;
encode = (options & Base64.ENCODE) == Base64.ENCODE;
bufferLength = encode ? 3 : 4;
buffer = new byte[bufferLength];
position = 0;
lineLength = 0;
suspendEncoding = false;
b4 = new byte[4];
this.options = options;
alphabet = Base64.getAlphabet(options);
decodabet = Base64.getDecodabet(options);
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
@Override
public void write(final int theByte) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theByte);
return;
} // end if: supsended
// Encode?
if (encode) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) // Enough to encode.
{
out.write(Base64.encode3to4(b4, buffer, bufferLength, options));
lineLength += 4;
if (breakLines && lineLength >= Base64.MAX_LINE_LENGTH) {
out.write(Base64.NEW_LINE);
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if (decodabet[theByte & 0x7f] > Base64.WHITE_SPACE_ENC) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) // Enough to output.
{
int len = Base64.decode4to3(buffer, 0, b4, 0, options);
out.write(b4, 0, len);
// out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if (decodabet[theByte & 0x7f] != Base64.WHITE_SPACE_ENC) {
throw new java.io.IOException("Invalid character in Base64 data.");
}
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write(final byte[] theBytes, final int off, final int len) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theBytes, off, len);
return;
} // end if: supsended
for (int i = 0; i < len; i++) {
write(theBytes[off + i]);
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
*/
public void flushBase64() throws java.io.IOException {
if (position > 0) {
if (encode) {
out.write(Base64.encode3to4(b4, buffer, position, options));
position = 0;
} // end if: encoding
else {
throw new java.io.IOException("Base64 input not properly padded.");
}
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
| 3,396 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/json/impl/Json.java
|
/*
* Copyright 2011-2012 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 com.netflix.paas.json.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.netflix.paas.json.DecodeException;
import com.netflix.paas.json.EncodeException;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class Json {
private static final Logger log = LoggerFactory.getLogger(Json.class);
private final static ObjectMapper mapper = new ObjectMapper();
private final static ObjectMapper prettyMapper = new ObjectMapper();
static {
// Non-standard JSON but we allow C style comments in our JSON
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
}
public static String encode(Object obj) throws EncodeException {
try {
return mapper.writeValueAsString(obj);
}
catch (Exception e) {
throw new EncodeException("Failed to encode as JSON: " + e.getMessage());
}
}
public static String encodePrettily(Object obj) throws EncodeException {
try {
return prettyMapper.writeValueAsString(obj);
} catch (Exception e) {
throw new EncodeException("Failed to encode as JSON: " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
public static <T> T decodeValue(String str, Class<?> clazz) throws DecodeException {
try {
return (T)mapper.readValue(str, clazz);
}
catch (Exception e) {
throw new DecodeException("Failed to decode:" + e.getMessage());
}
}
static {
prettyMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
}
}
| 3,397 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/index/Indexer.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.index;
public class Indexer {
}
| 3,398 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/service/SchemaService.java
|
/*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
******************************************************************************/
package com.netflix.paas.service;
import java.util.List;
import com.netflix.paas.entity.DbEntity;
import com.netflix.paas.entity.TableEntity;
/**
* Abstraction for registry of schemas and tables visible to this deployment
* @author elandau
*
*/
public interface SchemaService {
/**
* List schemas that are available to this instance
*
* @return
*/
List<DbEntity> listSchema();
/**
* List all tables in the schema
*
* @param schemaName
* @return
*/
List<TableEntity> listSchemaTables(String schemaName);
/**
* List all tables
*/
List<TableEntity> listAllTables();
/**
* Refresh from storage
*/
public void refresh();
}
| 3,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.