index
int64 0
0
| repo_id
stringlengths 26
205
| file_path
stringlengths 51
246
| content
stringlengths 8
433k
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
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);
}
| 600 |
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();
}
| 601 |
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;
}
}
| 602 |
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();
}
| 603 |
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;
}
}));
}
}
| 604 |
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;
}
}
| 605 |
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
}
}
| 606 |
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
}
}
| 607 |
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;
}
}
| 608 |
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;
}
}
| 609 |
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,
}
| 610 |
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();
}
| 611 |
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();
}
| 612 |
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;
}
| 613 |
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();
}
| 614 |
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;
}
| 615 |
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";
}
| 616 |
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();
}
}
| 617 |
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;
}
}
| 618 |
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;
}
}
| 619 |
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);
}
| 620 |
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;
}
}
| 621 |
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);
}
}
| 622 |
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);
}
}
| 623 |
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;
}
}
| 624 |
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;
}
}
| 625 |
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;
}
}
| 626 |
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;
}
}
| 627 |
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() {
}
}
| 628 |
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);
}
}
| 629 |
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
| 630 |
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);
}
}
| 631 |
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 {
}
| 632 |
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();
}
| 633 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/events/SchemaChangeEvent.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.events;
import com.netflix.paas.entity.DbEntity;
/**
* Event notifying that a schema has either been added, changed or removed
*
* @author elandau
*/
public class SchemaChangeEvent {
private final DbEntity schema;
private final boolean removed;
public SchemaChangeEvent(DbEntity schema, boolean removed) {
this.schema = schema;
this.removed = removed;
}
public DbEntity getSchema() {
return this.schema;
}
public boolean isExists() {
return removed;
}
}
| 634 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/data/RowData.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.data;
public class RowData {
private SchemaRows rows;
private SchemalessRows srows;
public SchemaRows getRows() {
return rows;
}
public void setRows(SchemaRows rows) {
this.rows = rows;
}
public SchemalessRows getSrows() {
return srows;
}
public void setSrows(SchemalessRows srows) {
this.srows = srows;
}
public boolean hasSchemalessRows() {
return this.srows != null;
}
public boolean hasSchemaRows() {
return this.rows != null;
}
@Override
public String toString() {
return "RowData [rows=" + rows + ", srows=" + srows + "]";
}
}
| 635 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/data/SchemalessRows.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.data;
import java.util.Map;
import com.google.common.collect.Maps;
/**
* Representation of rows as a sparse tree of rows to column value pairs
*
* @author elandau
*
*/
public class SchemalessRows {
public static class Builder {
private SchemalessRows rows = new SchemalessRows();
public Builder() {
rows.rows = Maps.newHashMap();
}
public Builder addRow(String row, Map<String, String> columns) {
rows.rows.put(row, columns);
return this;
}
public SchemalessRows build() {
return rows;
}
}
public static Builder builder() {
return new Builder();
}
private Map<String, Map<String, String>> rows;
public Map<String, Map<String, String>> getRows() {
return rows;
}
public void setRows(Map<String, Map<String, String>> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "SchemalessRows [rows=" + rows + "]";
}
}
| 636 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/data/QueryResult.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.data;
/**
* Representation of a query result which contains both the row data as well
* as the schema definition for the row
*
* @author elandau
*
*/
public class QueryResult {
private SchemaRows rows;
private SchemalessRows srows;
/**
* Cursor used to resume the call
* @note Optional
*/
private String cursor;
public String getCursor() {
return cursor;
}
public void setCursor(String cursor) {
this.cursor = cursor;
}
public SchemaRows getRows() {
return rows;
}
public void setRows(SchemaRows rows) {
this.rows = rows;
}
public SchemalessRows getSrows() {
return srows;
}
public void setSrows(SchemalessRows srows) {
this.srows = srows;
}
@Override
public String toString() {
return "QueryResult [rows=" + rows + ", srows=" + srows + ", cursor=" + cursor + "]";
}
}
| 637 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/data/SchemaRows.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.data;
import java.util.List;
/**
* Collection of rows using arrays to represent the data. All rows must
* have the same number of columns.
*
* @author elandau
*/
public class SchemaRows {
/**
* Names of the columns
*/
private List<String> names;
/**
* Data types for columns (ex. int, vchar, ...)
*/
private List<String> types;
/**
* Data rows as a list of column values. Index of column position must match
* index position in 'names' and 'types'
*/
private List<List<String>> rows;
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public List<String> getTypes() {
return types;
}
public void setTypes(List<String> types) {
this.types = types;
}
public List<List<String>> getRows() {
return rows;
}
public void setRows(List<List<String>> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "SchemaRows [names=" + names + ", types=" + types + ", rows="
+ rows + "]";
}
}
| 638 |
0 |
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/services
|
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/services/impl/DaoSchemaService.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.services.impl;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.netflix.paas.SchemaNames;
import com.netflix.paas.dao.Dao;
import com.netflix.paas.dao.DaoProvider;
import com.netflix.paas.entity.PassGroupConfigEntity;
import com.netflix.paas.entity.DbEntity;
import com.netflix.paas.entity.TableEntity;
import com.netflix.paas.events.SchemaChangeEvent;
import com.netflix.paas.resources.DataResource;
import com.netflix.paas.service.SchemaService;
/**
* Schema registry using a persistent DAO
*
* @author elandau
*
*/
public class DaoSchemaService implements SchemaService {
private final static Logger LOG = LoggerFactory.getLogger(DaoSchemaService.class);
private final DaoProvider daoProvider;
private final String groupName;
private final EventBus eventBus;
private Dao<PassGroupConfigEntity> groupDao;
private Dao<DbEntity> schemaDao;
private Map<String, DbEntity> schemas;
@Inject
public DaoSchemaService(@Named("groupName") String groupName, DataResource dataResource, DaoProvider daoProvider, EventBus eventBus) {
this.daoProvider = daoProvider;
this.groupName = groupName;
this.eventBus = eventBus;
}
@PostConstruct
public void initialize() throws Exception {
LOG.info("Initializing");
groupDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), PassGroupConfigEntity.class);
schemaDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), DbEntity.class);
try {
refresh();
}
catch (Exception e) {
LOG.error("Error refreshing schema list", e);
}
}
@Override
public List<DbEntity> listSchema() {
// return ImmutableList.copyOf(this.dao.list());
return null;
}
@Override
public List<TableEntity> listSchemaTables(String schemaName) {
return null;
}
@Override
public List<TableEntity> listAllTables() {
return null;
}
/**
* Refresh the schema list from the DAO
*/
@Override
public void refresh() {
LOG.info("Refreshing schema list for group: " + groupName);
PassGroupConfigEntity group = groupDao.read(groupName);
if (group == null) {
LOG.error("Failed to load configuration for group: " + groupName);
}
else {
Collection<DbEntity> foundEntities = schemaDao.read(group.getSchemas());
if (foundEntities.isEmpty()) {
LOG.warn("Not virtual schemas associated with group: " + groupName);
}
else {
for (DbEntity entity : foundEntities) {
LOG.info("Found schema : " + entity.getName());
if (entity.hasTables()) {
for (Entry<String, TableEntity> table : entity.getTables().entrySet()) {
LOG.info(" Found table : " + table.getKey());
}
}
eventBus.post(new SchemaChangeEvent(entity, false));
}
}
}
}
}
| 639 |
0 |
Create_ds/staash/staash-jetty/src/test/java/com/netflix
|
Create_ds/staash/staash-jetty/src/test/java/com/netflix/staash/SingletonEmbeddedCassandra.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.staash;
import com.netflix.astyanax.test.EmbeddedCassandra;
public class SingletonEmbeddedCassandra {
private final EmbeddedCassandra cassandra;
private static class Holder {
private final static SingletonEmbeddedCassandra instance = new SingletonEmbeddedCassandra();
}
public static SingletonEmbeddedCassandra getInstance() {
return Holder.instance;
}
public SingletonEmbeddedCassandra() {
try {
cassandra = new EmbeddedCassandra();
cassandra.start();
} catch (Exception e) {
throw new RuntimeException("Failed to start embedded cassandra", e);
}
}
public void finalize() {
try {
cassandra.stop();
}
catch (Exception e) {
}
}
}
| 640 |
0 |
Create_ds/staash/staash-jetty/src/test/java/com/netflix
|
Create_ds/staash/staash-jetty/src/test/java/com/netflix/staash/TestClassLoader.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.staash;
import java.net.URL;
import org.junit.Test;
public class TestClassLoader {
@Test
public void testLoader() {
String defaultConfigFileName1 = "config.properties";
String defaultConfigFileName2 = "/tmp/config.properties";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(defaultConfigFileName1);
URL url2 = loader.getResource(defaultConfigFileName1);
int i =0;
}
}
| 641 |
0 |
Create_ds/staash/staash-jetty/src/test/java/com/netflix
|
Create_ds/staash/staash-jetty/src/test/java/com/netflix/staash/TestSchemaData.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.staash;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.name.Names;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.paas.cassandra.discovery.EurekaAstyanaxHostSupplier;
import com.netflix.paas.cassandra.discovery.EurekaModule;
public class TestSchemaData {
private static final Logger LOG = LoggerFactory.getLogger(TestSchemaData.class);
private static final String groupName = "UnitTest2";
@BeforeClass
public static void startup() {
//SingletonEmbeddedCassandra.getInstance();
}
@AfterClass
public static void shutdown() {
}
@Test
@Ignore
public void test() throws Exception {
List<AbstractModule> modules = Lists.newArrayList(
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("groupName")).toInstance(groupName);
}
},
// new CassandraPaasModule(),
new EurekaModule()
// new PaasModule(),
// new JerseyServletModule() {
// @Override
// protected void configureServlets() {
// // Route all requests through GuiceContainer
// bind(GuiceContainer.class).asEagerSingleton();
// serve("/*").with(GuiceContainer.class);
// }
// },
// new AbstractModule() {
// @Override
// protected void configure() {
// bind(PaasBootstrap.class).asEagerSingleton();
// bind(PaasCassandraBootstrap.class).asEagerSingleton();
// }
// }
);
// Create the injector
Injector injector = LifecycleInjector.builder()
.withModules(modules)
.createInjector();
// LifecycleManager manager = injector.getInstance(LifecycleManager.class);
// manager.start();
//
// SchemaService schema = injector.getInstance(SchemaService.class);
// Assert.assertNotNull(schema);
// final String schemaName = "vschema1";
// final String tableName = "vt_CASS_SANDBOX_AstyanaxUnitTests_AstyanaxUnitTests|users";
//
//
// DataResource dataResource = injector .getInstance (DataResource.class);
// Assert.assertNotNull(dataResource);
//
// SchemaDataResource schemaResource = dataResource .getSchemaDataResource(schemaName);
// Assert.assertNotNull(schemaResource);
//
// TableDataResource tableResource = schemaResource.getTableSubresource (tableName);
// tableResource.listRows(null, 10, 10);
// ClusterDiscoveryService discoveryService = injector.getInstance(ClusterDiscoveryService.class);
// LOG.info("Clusters: " + discoveryService.getClusterNames());
EurekaAstyanaxHostSupplier supplier = injector.getInstance(EurekaAstyanaxHostSupplier.class);
Supplier<List<Host>> list1 = supplier.getSupplier("cass_sandbox");
List<Host> hosts = list1.get();
LOG.info("cass_sandbox");
for (Host host:hosts) {
LOG.info(host.getHostName());
}
Supplier<List<Host>> list2 = supplier.getSupplier("ABCLOUD");
hosts = list2.get();
LOG.info("ABCLOUD");
for (Host host:hosts) {
LOG.info(host.getHostName());
}
Supplier<List<Host>> list3 = supplier.getSupplier("CASSS_PAAS");
hosts = list3.get();
LOG.info("casss_paas");
for (Host host:hosts) {
LOG.info(host.getHostName());
}
// CassandraSystemAdminResource admin = injector.getInstance(CassandraSystemAdminResource.class);
// admin.discoverClusters();
LOG.info("starting cluster discovery task");
// TaskManager taskManager = injector.getInstance(TaskManager.class);
// taskManager.submit(ClusterDiscoveryTask.class);
//
// PassGroupConfigEntity.Builder groupBuilder = PassGroupConfigEntity.builder().withName(groupName);
//
// String keyspaceName = "AstyanaxUnitTests";
// int i = 0;
// String vschemaName = "vschema1";
// DbEntity.Builder virtualSchemaBuilder = DbEntity.builder()
// .withName(vschemaName);
//
//
//
LOG.info("running cluster dao");
// DaoProvider daoManager = injector.getInstance(Key.get(DaoProvider.class));
// DaoKeys key;
// Dao<CassandraClusterEntity> cassClusterDAO = daoManager.getDao(DaoKeys.DAO_CASSANDRA_CLUSTER_ENTITY);
// Collection<CassandraClusterEntity> cassClusterColl = cassClusterDAO.list();
// for (CassandraClusterEntity cse: cassClusterColl) {
// LOG.info(cse.getClusterName());
// }
// for (String cfName : cassCluster.getKeyspaceColumnFamilyNames(keyspaceName)) {
// LOG.info(cfName);
// TableEntity table = TableEntity.builder()
// .withTableName(StringUtils.join(Lists.newArrayList("vt", clusterName, keyspaceName, cfName), "_"))
// .withStorageType("cassandra")
// .withOption("cassandra.cluster", clusterName)
// .withOption("cassandra.keyspace", keyspaceName)
// .withOption("cassandra.columnfamily", cfName)
// .build();
//
// virtualSchemaBuilder.addTable(table);
// }
//
// vschemaDao.write(virtualSchemaBuilder.build());
//
// groupDao.write(groupBuilder.build());
// DaoManager daoManager = injector.getInstance(Key.get(DaoManager.class, Names.named("configuration")));
// Dao<VirtualSchemaEntity> schemaDao = daoManager.getDao(VirtualSchemaEntity.class);
//
// List<Dao<?>> daos = daoManager.listDaos();
// Assert.assertEquals(1, daos.size());
//
// for (Dao<?> dao : daos) {
// LOG.info("Have DAO " + dao.getDaoType() + ":" + dao.getEntityType());
// dao.createStorage();
// }
//
// DaoSchemaRegistry schemaService = injector.getInstance(DaoSchemaRegistry.class);
// schemaService.listSchema();
//
// DaoManager daoFactory = injector.getInstance(DaoManager.class);
//
//// Dao<SchemaEntity> schemaEntityDao = daoFactory.getDao(SchemaEntity.class);
//// schemaEntityDao.createStorage();
//// schemaEntityDao.write(SchemaEntity.builder()
//// .withName("schema1")
//// .addTable(TableEntity.builder()
//// .withStorageType("cassandra")
//// .withTableName("table1")
//// .withSchemaName("schema1")
//// .withOption("clusterName", "local")
//// .withOption("keyspaceName", "Keyspace1")
//// .withOption("columnFamilyName", "ColumnFamily1")
//// .build())
//// .build());
//
//// Iterable<SchemaEntity> schemas = schemaEntityDao.list();
//// for (SchemaEntity entity : schemas) {
//// System.out.println(entity.toString());
//// }
// manager.close();
}
}
| 642 |
0 |
Create_ds/staash/staash-jetty/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-jetty/src/main/java/com/netflix/staash/jetty/PaasGuiceServletConfig.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.staash.jetty;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.name.Names;
import com.google.inject.servlet.GuiceServletContextListener;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.paas.PaasBootstrap;
import com.netflix.paas.PaasModule;
import com.netflix.paas.cassandra.CassandraPaasModule;
import com.netflix.paas.cassandra.MetaCassandraBootstrap;
import com.netflix.paas.cassandra.MetaModule;
import com.netflix.paas.cassandra.PaasCassandraBootstrap;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
public class PaasGuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return LifecycleInjector.builder()
.withModules(
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("groupName")).toInstance("UnitTest1");
bind(String.class).annotatedWith(Names.named("clustername")).toInstance("localhost");
}
},
new CassandraPaasModule(),
new MetaModule(),
//new EurekaModule(),
new PaasModule(),
new JerseyServletModule() {
@Override
protected void configureServlets() {
// Route all requests through GuiceContainer
bind(GuiceContainer.class).asEagerSingleton();
serve("/*").with(GuiceContainer.class);
}
},
new AbstractModule() {
@Override
protected void configure() {
bind(MetaCassandraBootstrap.class).asEagerSingleton();
bind(PaasBootstrap.class).asEagerSingleton();
bind(PaasCassandraBootstrap.class).asEagerSingleton();
}
}
)
.createInjector();
}
}
| 643 |
0 |
Create_ds/staash/staash-jetty/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-jetty/src/main/java/com/netflix/staash/jetty/NewPaasGuiceServletConfig.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.staash.jetty;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.paas.cassandra.MetaCassandraBootstrap;
import com.netflix.paas.cassandra.MetaModule;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
public class NewPaasGuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return LifecycleInjector.builder()
.withModules(
new MetaModule(),
//new EurekaModule(),
new JerseyServletModule() {
@Override
protected void configureServlets() {
// Route all requests through GuiceContainer
bind(GuiceContainer.class).asEagerSingleton();
serve("/*").with(GuiceContainer.class);
}
},
new AbstractModule() {
@Override
protected void configure() {
bind(MetaCassandraBootstrap.class).asEagerSingleton();
}
}
)
.createInjector();
}
}
| 644 |
0 |
Create_ds/staash/staash-jetty/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-jetty/src/main/java/com/netflix/staash/jetty/PaasLauncher.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.staash.jetty;
import org.eclipse.jetty.server.Server;
import com.google.inject.servlet.GuiceFilter;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PaasLauncher {
private static final Logger LOG = LoggerFactory.getLogger(PaasLauncher.class);
private static final int DEFAULT_PORT = 8080;
public static void main(String[] args) throws Exception {
LOG.info("Starting PAAS");
// Create the server.
Server server = new Server(DEFAULT_PORT);
// Create a servlet context and add the jersey servlet.
ServletContextHandler sch = new ServletContextHandler(server, "/");
// Add our Guice listener that includes our bindings
sch.addEventListener(new PaasGuiceServletConfig());
// Then add GuiceFilter and configure the server to
// reroute all requests through this filter.
sch.addFilter(GuiceFilter.class, "/*", null);
// Must add DefaultServlet for embedded Jetty.
// Failing to do this will cause 404 errors.
// This is not needed if web.xml is used instead.
sch.addServlet(DefaultServlet.class, "/");
// Start the server
server.start();
server.join();
LOG.info("Stopping PAAS");
}
}
| 645 |
0 |
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest
|
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest/test/TestPaasPropertiesModule.java
|
package com.netflix.paas.rest.test;
import java.net.URL;
import java.util.Properties;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.policies.RoundRobinPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
import com.netflix.staash.cassandra.discovery.EurekaAstyanaxHostSupplier;
import com.netflix.staash.connection.ConnectionFactory;
import com.netflix.staash.connection.PaasConnectionFactory;
import com.netflix.staash.rest.dao.AstyanaxDataDaoImpl;
import com.netflix.staash.rest.dao.AstyanaxMetaDaoImpl;
import com.netflix.staash.rest.dao.CqlDataDaoImpl;
import com.netflix.staash.rest.dao.CqlMetaDaoImpl;
import com.netflix.staash.rest.dao.CqlMetaDaoImplNew;
import com.netflix.staash.rest.dao.DataDao;
import com.netflix.staash.rest.dao.MetaDao;
import com.netflix.staash.rest.util.HostSupplier;
import com.netflix.staash.rest.util.MetaConstants;
import com.netflix.staash.service.CacheService;
import com.netflix.staash.service.DataService;
import com.netflix.staash.service.MetaService;
import com.netflix.staash.service.PaasDataService;
import com.netflix.staash.service.PaasMetaService;
public class TestPaasPropertiesModule extends AbstractModule {
@Override
protected void configure() {
try {
Properties props = loadProperties();
Names.bindProperties(binder(), props);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Properties loadProperties() throws Exception {
Properties properties = new Properties();
ClassLoader loader = TestPaasPropertiesModule.class.getClassLoader();
URL url = loader.getResource("paas.properties");
properties.load(url.openStream());
return properties;
}
@Provides
@Named("metacluster")
Cluster provideCluster(@Named("paas.cassclient") String clientType,@Named("paas.metacluster") String clustername) {
if (clientType.equals("cql")) {
Cluster cluster = Cluster.builder().addContactPoint(clustername).build();
return cluster;
} else return null;
}
@Provides
HostSupplier provideHostSupplier(@Named("paas.metacluster") String clustername) {
return null;
}
@Provides
@Named("astmetaks")
@Singleton
Keyspace provideKeyspace(@Named("paas.metacluster") String clustername) {
String clusterNameOnly = "";
String clusterPortOnly = "";
String[] clusterinfo = clustername.split(":");
if (clusterinfo != null && clusterinfo.length == 2) {
clusterNameOnly = clusterinfo[0];
clusterPortOnly = clusterinfo[1];
} else {
clusterNameOnly = clustername;
clusterPortOnly = "9160";
}
// hs = new EurekaAstyanaxHostSupplier();
AstyanaxContext<Keyspace> keyspaceContext = new AstyanaxContext.Builder()
.forCluster(clusterNameOnly)
.forKeyspace(MetaConstants.META_KEY_SPACE)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl()
.setDiscoveryType(
NodeDiscoveryType.RING_DESCRIBE)
.setConnectionPoolType(
ConnectionPoolType.TOKEN_AWARE)
.setDiscoveryDelayInSeconds(60000)
.setTargetCassandraVersion("1.1")
.setCqlVersion("3.0.0"))
// .withHostSupplier(hs.getSupplier(clustername))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl(clusterNameOnly
+ "_" + MetaConstants.META_KEY_SPACE)
.setSocketTimeout(3000)
.setMaxTimeoutWhenExhausted(2000)
.setMaxConnsPerHost(3).setInitConnsPerHost(1)
.setSeeds(clusterNameOnly+":"+clusterPortOnly)) //uncomment for localhost
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
keyspaceContext.start();
Keyspace keyspace;
keyspace = keyspaceContext.getClient();
return keyspace;
}
@Provides
@Named("datacluster")
Cluster provideDataCluster(@Named("paas.datacluster") String clustername) {
Cluster cluster = Cluster.builder().addContactPoint(clustername).build();
return cluster;
}
@Provides
@Singleton
MetaDao provideCqlMetaDao(@Named("paas.cassclient") String clientType, @Named("metacluster") Cluster cluster,@Named("astmetaks") Keyspace keyspace) {
if (clientType.equals("cql"))
return new CqlMetaDaoImpl(cluster );
else return new AstyanaxMetaDaoImpl(keyspace);
}
@Provides
DataDao provideCqlDataDao(@Named("paas.cassclient") String clientType, @Named("datacluster") Cluster cluster, MetaDao meta) {
if (clientType.equals("cql"))
return new CqlDataDaoImpl(cluster, meta);
else return new AstyanaxDataDaoImpl();
}
@Provides
@Named("pooledmetacluster")
Cluster providePooledCluster(@Named("paas.cassclient") String clientType,@Named("paas.metacluster") String clustername) {
if (clientType.equals("cql")) {
Cluster cluster = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).addContactPoint(clustername).build();
// Cluster cluster = Cluster.builder().addContactPoint(clustername).build();
return cluster;
}else {
return null;
}
}
@Provides
@Named("newmetadao")
@Singleton
MetaDao provideCqlMetaDaoNew(@Named("paas.cassclient") String clientType, @Named("metacluster") Cluster cluster, @Named("astmetaks") Keyspace keyspace) {
if (clientType.equals("cql"))
return new CqlMetaDaoImplNew(cluster );
else return new AstyanaxMetaDaoImpl(keyspace);
}
@Provides
MetaService providePaasMetaService(@Named("newmetadao") MetaDao metad, ConnectionFactory fac, CacheService cache) {
PaasMetaService metasvc = new PaasMetaService(metad, fac, cache);
return metasvc;
}
@Provides
DataService providePaasDataService( MetaService metasvc, ConnectionFactory fac) {
PaasDataService datasvc = new PaasDataService(metasvc, fac);
return datasvc;
}
@Provides
CacheService provideCacheService(@Named("newmetadao") MetaDao metad) {
return new CacheService(metad);
}
@Provides
ConnectionFactory provideConnectionFactory(@Named("paas.cassclient") String clientType, EurekaAstyanaxHostSupplier hs) {
return new PaasConnectionFactory(clientType, hs);
}
}
| 646 |
0 |
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest
|
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest/test/TestPaasApis.java
|
package com.netflix.paas.rest.test;
import org.junit.Test;
import com.netflix.staash.json.JsonArray;
import com.netflix.staash.json.JsonObject;
public class TestPaasApis {
@Test
public void testJsonArr() {
String eventsStr = "[{\"name\":\"me\"},{\"name\":\"you\"}]";
String eventStr = "{\"name\":\"me\"}";
try {
JsonObject jObj = new JsonObject(eventStr);
int i = 0;
System.out.println(jObj.isArray());
}catch (Exception e) {
e.printStackTrace();
}
JsonArray evts1 = new JsonArray(eventsStr);
JsonArray events = new JsonArray();
events.addString(eventsStr);
// if (events.isArray()) {
// JsonArray eventsArr = events.asArray();
// JsonObject obj;
// for (int i=0;obj = events.get(i); i++) {
// JsonObject obj = (JsonObject) event;
// }
// }
Object obj1 = evts1.get(0);
Object obj2 = evts1.get(1);
int len = evts1.size();
int i = 0;
}
}
| 647 |
0 |
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest
|
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest/test/TestPaasRest.java
|
package com.netflix.paas.rest.test;
import java.util.Random;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.netflix.staash.cassandra.discovery.EurekaModule;
import com.netflix.staash.exception.StorageDoesNotExistException;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.rest.meta.entity.EntityType;
import com.netflix.staash.service.PaasDataService;
import com.netflix.staash.service.PaasMetaService;
public class TestPaasRest {
PaasMetaService metasvc;
PaasDataService datasvc;
@Before
public void setup() {
// metasvc = new PaasMetaService(new CqlMetaDaoImplNew(Cluster.builder().addContactPoint("localhost").build()));
EurekaModule em = new EurekaModule();
Injector einj = Guice.createInjector(em);
TestPaasPropertiesModule pmod = new TestPaasPropertiesModule();
Injector inj = Guice.createInjector(pmod);
metasvc = inj.getInstance(PaasMetaService.class);
// datasvc = new PaasDataService(metasvc, Guice.createInjector(pmod).getInstance(ConnectionFactory.class));
datasvc = inj.getInstance(PaasDataService.class);
}
@Test
@Ignore
public void createStorage() {
String payload = "{\"name\": \"social_nosql_storage\",\"type\": \"cassandra\",\"cluster\": \"cass_social\",\"replicate\":\"another\"}";
String s;
try {
s = metasvc.writeMetaEntity(EntityType.STORAGE, payload);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Print(s);
}
private void Print(String s) {
System.out.println(s);
}
@Test
@Ignore
public void testCreateDb() {
//name
//meta.writerow(dbentity)
String payload = "{\"name\":\"unitdb1\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, payload);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
@Ignore
public void testCreateTable() {
String storage = "{\"name\": \"unit.mysql\",\"type\": \"mysql\",\"jdbcurl\": \"jdbc:mysql://localhost:3306/\",\"host\":\"localhost\",\"user\":\"netflix\",\"password\":\"\",\"oss\":\"another\"}";
try {
metasvc.writeMetaEntity(EntityType.STORAGE, storage);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dbpay = "{\"name\":\"unitdb2\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tblpay = "{\"name\":\"unittbl2\",\"columns\":\"col1,col2,col3\",\"primarykey\":\"col1\",\"storage\":\"unit.mysql\"}";
String db = "unitdb2";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
@Ignore
public void testCreateTableCass() {
String storage = "{\"name\": \"unit.cassandra\",\"type\": \"cassandra\",\"cluster\": \"localhost\",\"replicate\":\"another\"}";
try {
metasvc.writeMetaEntity(EntityType.STORAGE, storage);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dbpay = "{\"name\":\"unitdb2\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tblpay = "{\"name\":\"tst2\",\"columns\":\"col1,col2,col3\",\"primarykey\":\"col1\",\"storage\":\"unit.cassandra\"}";
String db = "unitdb2";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
@Ignore
public void listTablesInaSchema() {
}
@Test
@Ignore
public void testInsertRow() {
String storage = "{\"name\": \"unit.cassandra\",\"type\": \"cassandra\",\"cluster\": \"localhost\",\"replicate\":\"another\"}";
try {
metasvc.writeMetaEntity(EntityType.STORAGE, storage);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dbpay = "{\"name\":\"unitcass\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tblpay = "{\"name\":\"casstable1\",\"columns\":\"col1,col2,col3\",\"primarykey\":\"col1\",\"storage\":\"unit.cassandra\"}";
String db = "unitcass";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String insertPay = "{\"columns\":\"col1,col2,col3\",\"values\":\"'val1','val2','val3'\"}";
datasvc.writeRow(db, "casstable1", new JsonObject(insertPay));
}
@Test
@Ignore
public void testInsertRowMySql() {
String storage = "{\"name\": \"unit.mysql\",\"type\": \"mysql\",\"jdbcurl\": \"jdbc:mysql://localhost:3306/\",\"host\":\"localhost\",\"user\":\"dummy\",\"password\":\"\",\"dummy\":\"another\"}";
try {
metasvc.writeMetaEntity(EntityType.STORAGE, storage);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dbpay = "{\"name\":\"unitdb3\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tblpay = "{\"name\":\"my2\",\"columns\":\"col1,col2,col3\",\"primarykey\":\"col1\",\"storage\":\"unit.mysql\"}";
String db = "unitdb3";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String insertPay = "{\"columns\":\"col1,col2,col3\",\"values\":\"'val1','val2','val3'\"}";
datasvc.writeRow(db, "my2", new JsonObject(insertPay));
}
@Test
@Ignore
public void testInsertRowMySqlRemote() {
String storage = "{\"name\": \"unit.mysqlremote\",\"type\": \"mysql\",\"jdbcurl\": \"jdbc:mysql://test.ceqg1dgfu0mp.useast1.rds.amazonaws.com:3306/\",\"host\":\"test.ceqg1dgfu0mp.useast-1.rds.amazonaws.com\",\"user\":\"dummy\",\"password\":\"dummy\",\"replicate\":\"another\"}";
try {
metasvc.writeMetaEntity(EntityType.STORAGE, storage);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dbpay = "{\"name\":\"unitdb3\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tblpay = "{\"name\":\"my2\",\"columns\":\"col1,col2,col3\",\"primarykey\":\"col1\",\"storage\":\"unit.mysqlremote\"}";
String db = "unitdb3";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String insertPay = "{\"columns\":\"col1,col2,col3\",\"values\":\"'val1','val2','val3'\"}";
datasvc.writeRow(db, "my2", new JsonObject(insertPay));
}
@Test
@Ignore
public void testRemoteJoin() {
long start = System.currentTimeMillis();
String clustername = "ec2-54-242-127-138.compute-1.amazonaws.com";
String storage = "{\"name\": \"unit.remotecassandra\",\"type\": \"cassandra\",\"cluster\": \"ec2-54-242-127-138.compute-1.amazonaws.com:7102\",\"replicate\":\"another\"}";
try {
metasvc.writeMetaEntity(EntityType.STORAGE, storage);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Print("Storage:"+(System.currentTimeMillis() - start));
String dbpay = "{\"name\":\"jointest\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Print("db:"+(System.currentTimeMillis() - start));
String table1="cassjoin"+ new Random().nextInt(200);
String tblpay = "{\"name\":\""+table1+"\",\"columns\":\"username,friends,wall,status\",\"primarykey\":\"username\",\"storage\":\"unit.remotecassandra\"}";
String db = "jointest";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Print("table:"+(System.currentTimeMillis() - start));
String insertPay = "{\"columns\":\"username,friends,wall,status\",\"values\":\"'federer','rafa#haas#tommy#sachin#beckham','getting ready for my next#out of wimbledon#out of french','looking fwd to my next match'\"}";
datasvc.writeRow(db, table1, new JsonObject(insertPay));
Print("insert cass:"+(System.currentTimeMillis() - start));
String table2="mysqljoin" + new Random().nextInt(200);;
tblpay = "{\"name\":\""+table2+"\",\"columns\":\"username,first,last,lastlogin,paid,address,email\",\"primarykey\":\"username\",\"storage\":\"unit.mysqlremote\"}";
pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Print("create mysql table:"+(System.currentTimeMillis() - start));
insertPay = "{\"columns\":\"username,first,last,lastlogin,paid,address,email\",\"values\":\"'federer','Roger','Federer','july first','paid','1 swiss drive','[email protected]'\"}";
datasvc.writeRow(db, table2, new JsonObject(insertPay));
Print("insert mysql row:"+(System.currentTimeMillis() - start));
String str = datasvc.doJoin(db, table1, table2, "username", "rogerfederer");
Print("Join:"+(System.currentTimeMillis() - start));
Print("Join is");
Print(str);
}
@Test
@Ignore
public void testjoin1()
{
String str = datasvc.doJoin("jointest", "mysqljoin43", "cassjoin78", "username", "federer");
// Print("Join:"+(System.currentTimeMillis() - start));
Print("Join is");
Print(str);
}
@Test
@Ignore
public void testJoin() {
// String clustername = "localhost";
// String storage = "{\"name\": \"unit.cassandra\",\"type\": \"cassandra\",\"cluster\": \"localhost\",\"replicate\":\"another\"}";
// metasvc.writeMetaEntity(EntityType.STORAGE, storage);
String dbpay = "{\"name\":\"ljointest\"}";
try {
metasvc.writeMetaEntity(EntityType.DB, dbpay);
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String table1="join1";
String tblpay = "{\"name\":\"join1\",\"columns\":\"username,friends,wall,status\",\"primarykey\":\"username\",\"storage\":\"unit.cassandra\"}";
String db = "jointest";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String insertPay = "{\"columns\":\"username,friends,wall,status\",\"values\":\"'rogerfederer','rafa#haas#tommy#sachin#beckham','getting ready for my next#out of wimbledon#out of french','looking fwd to my next match'\"}";
datasvc.writeRow(db, "join1", new JsonObject(insertPay));
String table2="join2";
tblpay = "{\"name\":\"join2\",\"columns\":\"username,first,last,lastlogin,paid,address,email\",\"primarykey\":\"username\",\"storage\":\"unit.mysql\"}";
pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.TABLE, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = datasvc.doJoin(db, table1, table2, "username", "rogerfederer");
Print(str);
}
@Test
@Ignore
public void testCreateTimeseriesTable() {
String tblpay = "{\"name\":\"timeseries1\",\"periodicity\":\"10000\",\"prefix\":\"server1\",\"storage\":\"unit.cassandra\"}";
String db = "unitdb2";
JsonObject pload = new JsonObject(tblpay);
pload.putString("db", db);
try {
metasvc.writeMetaEntity(EntityType.SERIES, pload.toString());
} catch (StorageDoesNotExistException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
@Ignore
public void insertEvent() {
String db = "unitdb2";
String table = "timeseries1";
String payload1="{\"time\":11000,\"event\":\"hello 11k event\"}";
String payload2="{\"time\":21000,\"event\":\"hi 21k event\"}";
datasvc.writeEvent(db, table, new JsonObject(payload1));
datasvc.writeEvent(db, table, new JsonObject(payload2));
}
@Test
@Ignore
public void readEvent() {
String evtime = "11000";
String db = "unitdb2";
String table = "timeseries1";
String out;
out = datasvc.readEvent(db, table, evtime);
out = datasvc.readEvent(db, table, "21000");
out = datasvc.readEvent(db, table, "100000");
int i = 0;
}
@Test
@Ignore
public void listStorage() {
String out = metasvc.listStorage();
Print(out);
}
@Test
@Ignore
public void listSchemas() {
String out = metasvc.listSchemas();
Print(out);
}
@Test
@Ignore
public void listTablesInSchema() {
String out = metasvc.listTablesInSchema("unitdb2");
Print(out);
}
@Test
@Ignore
public void listTimeseriesInSchema() {
String out = metasvc.listTimeseriesInSchema("unitdb2");
Print(out);
}
@Test
@Ignore
public void testInsertColumn() {
}
@Test
@Ignore
public void testUpdateRow() {
}
@Test
@Ignore
public void testDeleteRow() {
}
@Test
@Ignore
public void testDeleteColumn() {
}
@Test
@Ignore
public void testQuery() {
}
@Test
@Ignore
public void runMrJob() {
}
}
| 648 |
0 |
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest
|
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest/test/PaasTestHelper.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.rest.test;
public class PaasTestHelper {
public static final String ServerUrl = "http://localhost:8080";
public static final String CreateDBUrl = "/staash/v1/admin";
public static final String CreateDBPayload = "{name: testdb}";
public static final String ListDBUrl = "/staash/v1/admin";
public static final String CreateStorageUrl = "http://localhost:8080/paas/v1/admin/storage";
public static final String CreateStoragePayloadCassandra = "{name:testStorageCass, type: cassandra, cluster:local, replicateto:newcluster";
public static final String ListStorage = "/staash/v1/admin/storage";
public static final String CreateTableUrl = "/staash/v1/admin/testdb";
public static final String CreateTablePayload = "{name:testtable, columns:user,friends,wall,status, primarykey:user, storage: teststoagecass}";
public static final String ListTablesUrl = "/staash/v1/admin/testdb";
public static final String InsertRowUrl = "/staash/v1/data/testdb/testtable";
public static final String InserRowUrlPayload = "{columns:user,friends,wall,status,values:rogerfed,rafanad,blahblah,blahblahblah}";
public static final String ReadRowUrl = "/staash/v1/data/testdb/testtable/username/rogerfed";
public static final String CreateTimeSeriesUrl = "/staash/v1/admin/timeseries/testdb";
public static final String CreateTimeSeriesPayload = "{\"name\":\"testseries\",\"msperiodicity\":10000,\"prefix\":\"rogerfed\"}";
public static final String ListTimeSeriesUrl = "/staash/v1/admin/timeseries/testdb";
public static final String CreateEventUrl = "/staash/v1/admin/timeseries/testdb/testseries";
public static final String CreateEventPayload = "{\"time\":1000000,\"event\":\"{tweet: enjoying a cruise}}\"";
public static final String ReadEventUrl = "/staash/v1/data/timeseries/testdb/testseries/time/100000/prefix/rogerfed";
}
| 649 |
0 |
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest
|
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest/test/PaasEurekaNodeDiscoveryTest.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.rest.test;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.name.Names;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.staash.cassandra.discovery.EurekaAstyanaxHostSupplier;
import com.netflix.staash.cassandra.discovery.EurekaModule;
public class PaasEurekaNodeDiscoveryTest {
Logger LOG = LoggerFactory.getLogger(PaasEurekaNodeDiscoveryTest.class);
@Test
@Ignore
public void testSupplier() {
List<AbstractModule> modules = Lists.newArrayList(
new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("groupName")).toInstance("testgroup");
}
},
new EurekaModule()
);
// Create the injector
Injector injector = LifecycleInjector.builder()
.withModules(modules)
.createInjector();
EurekaAstyanaxHostSupplier supplier = injector.getInstance(EurekaAstyanaxHostSupplier.class);
// EurekaAstyanaxHostSupplier supplier = new EurekaAstyanaxHostSupplier();
Supplier<List<Host>> list1 = supplier.getSupplier("c_sandbox");
List<Host> hosts = list1.get();
LOG.info("cass_sandbox");
for (Host host:hosts) {
LOG.info(host.getHostName());
}
// Supplier<List<Host>> list2 = supplier.getSupplier("ABCLOUD");
// hosts = list2.get();
// LOG.info("ABCLOUD");
// for (Host host:hosts) {
// LOG.info(host.getHostName());
// }
Supplier<List<Host>> list3 = supplier.getSupplier("C_PAAS");
hosts = list3.get();
LOG.info("c_paas");
for (Host host:hosts) {
LOG.info(host.getHostName());
}
}
}
| 650 |
0 |
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest
|
Create_ds/staash/staash-svc/src/test/java/com/netflix/paas/rest/test/TimeSeriesTest.java
|
package com.netflix.paas.rest.test;
import org.junit.Before;
import org.junit.Test;
public class TimeSeriesTest {
public static final String STAASH_URL = "http://localhost:8080/staash/v1/data/timeseries";
public static final String TIME_SERIES = "timeseries";
public static final String DB = "timeseriesdb";
public static final Integer INSERTION_SIZE = 10000;
public static final Integer PERIODICITY = 3600000;
public static final String START_DATE = "01-01-2014";
public static final String Start_Time = "00:00:00";
public static final String End_Time = "23:59:59";
@Before
public void setup() {
}
@Test
public void insert() {
}
@Test
public void read() {
}
}
| 651 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/AstyanaxCassandraConnection.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.staash.connection;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.google.common.collect.ImmutableMap;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.cql.CqlStatementResult;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.recipes.storage.CassandraChunkedStorageProvider;
import com.netflix.astyanax.recipes.storage.ChunkedStorage;
import com.netflix.astyanax.recipes.storage.ChunkedStorageProvider;
import com.netflix.astyanax.recipes.storage.ObjectMetadata;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
import com.netflix.staash.cassandra.discovery.EurekaAstyanaxHostSupplier;
import com.netflix.staash.common.query.QueryFactory;
import com.netflix.staash.common.query.QueryType;
import com.netflix.staash.common.query.QueryUtils;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.model.StorageType;
public class AstyanaxCassandraConnection implements PaasConnection {
private Keyspace keyspace;
private static Logger logger = Logger
.getLogger(AstyanaxCassandraConnection.class);
public AstyanaxCassandraConnection(String cluster, String db,
EurekaAstyanaxHostSupplier supplier) {
this.keyspace = createAstyanaxKeyspace(cluster, db, supplier);
}
private Keyspace createAstyanaxKeyspace(String clustername, String db,
EurekaAstyanaxHostSupplier supplier) {
String clusterNameOnly = "localhost";
String clusterPortOnly = "9160";
String[] clusterinfo = clustername.split(":");
if (clusterinfo != null && clusterinfo.length == 2) {
clusterNameOnly = clusterinfo[0];
} else {
clusterNameOnly = clustername;
}
AstyanaxContext<Keyspace> keyspaceContext;
if (supplier!=null) {
keyspaceContext = new AstyanaxContext.Builder()
.forCluster("Casss_Paas")
.forKeyspace(db)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl()
.setDiscoveryType(
NodeDiscoveryType.DISCOVERY_SERVICE)
.setConnectionPoolType(
ConnectionPoolType.TOKEN_AWARE)
.setDiscoveryDelayInSeconds(60)
.setTargetCassandraVersion("1.2")
.setCqlVersion("3.0.0"))
.withHostSupplier(supplier.getSupplier(clustername))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl(clusterNameOnly
+ "_" + db)
.setSocketTimeout(10000)
.setPort(7102)
.setMaxConnsPerHost(10).setInitConnsPerHost(3)
.setSeeds(null))
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
} else {
keyspaceContext = new AstyanaxContext.Builder()
.forCluster(clusterNameOnly)
.forKeyspace(db)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl()
.setDiscoveryType(
NodeDiscoveryType.RING_DESCRIBE)
.setConnectionPoolType(
ConnectionPoolType.TOKEN_AWARE)
.setDiscoveryDelayInSeconds(60)
.setTargetCassandraVersion("1.2")
.setCqlVersion("3.0.0"))
//.withHostSupplier(hs.getSupplier(clustername))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl(clusterNameOnly
+ "_" + db)
.setSocketTimeout(11000)
.setConnectTimeout(2000)
.setMaxConnsPerHost(10).setInitConnsPerHost(3)
.setSeeds(clusterNameOnly+":"+clusterPortOnly))
.buildKeyspace(ThriftFamilyFactory.getInstance());
}
keyspaceContext.start();
Keyspace keyspace;
keyspace = keyspaceContext.getClient();
return keyspace;
}
public String insert(String db, String table, JsonObject payload) {
try {
// if (payload.getString("type").equals("kv")) {
// String str = Hex.bytesToHex(payload.getBinary("value"));
// String stmt = "insert into " + db + "." + table
// + "(key, value)" + " values('"
// + payload.getString("key") + "' , '" + str + "');";
// keyspace.prepareCqlStatement().withCql(stmt).execute();
// } else {
String query = QueryFactory.BuildQuery(QueryType.INSERT,
StorageType.CASSANDRA);
keyspace.prepareCqlStatement()
.withCql(
String.format(query, db + "." + table,
payload.getString("columns"),
payload.getValue("values"))).execute();
// }
} catch (ConnectionException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return "{\"message\":\"ok\"}";
}
public String writeChunked(String db, String table, String objectName,
InputStream is) {
ChunkedStorageProvider provider = new CassandraChunkedStorageProvider(
keyspace, table);
ObjectMetadata meta;
try {
// if (is!=null) is.reset();
meta = ChunkedStorage.newWriter(provider, objectName, is)
.withChunkSize(0x40000).withConcurrencyLevel(8)
.withMaxWaitTime(10).call();
if (meta != null && meta.getObjectSize() <= 0)
throw new RuntimeException("Object does not exist");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return "{\"msg\":\"ok\"}";
}
public ByteArrayOutputStream readChunked(String db, String table, String objName) {
ChunkedStorageProvider provider = new CassandraChunkedStorageProvider(
keyspace, table);
ObjectMetadata meta;
ByteArrayOutputStream os = null;
try {
meta = ChunkedStorage.newInfoReader(provider, objName).call();
os = new ByteArrayOutputStream(meta.getObjectSize().intValue());
meta = ChunkedStorage.newReader(provider, objName, os)
.withConcurrencyLevel(8).withMaxWaitTime(10)
.withBatchSize(10).call();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return os;
}
public String createDB(String dbInfo) {
JsonObject dbJson = new JsonObject(dbInfo);
try {
String rfString = dbJson.getString("rf");
String strategy = dbJson.getString("strategy");
String[] rfs = rfString.split(",");
Map<String, Object> strategyMap = new HashMap<String, Object>();
for (int i = 0; i < rfs.length; i++) {
String[] rfparams = rfs[i].split(":");
strategyMap.put(rfparams[0], (Object) rfparams[1]);
}
keyspace.createKeyspace(ImmutableMap.<String, Object> builder()
.put("strategy_options", strategyMap)
.put("strategy_class", strategy).build());
} catch (Exception e) {
logger.info("DB Exists, Skipping");
}
return "{\"message\":\"ok\"}";
}
public String createTable(JsonObject payload) {
String sql = String
.format(QueryFactory.BuildQuery(QueryType.CREATETABLE,
StorageType.CASSANDRA), payload.getString("db") + "."
+ payload.getString("name"), QueryUtils.formatColumns(
payload.getString("columns"), StorageType.CASSANDRA),
payload.getString("primarykey"));
try {
keyspace.prepareCqlStatement().withCql(sql + ";").execute();
} catch (ConnectionException e) {
logger.info("Table Exists, Skipping");
}
return "{\"message\":\"ok\"}";
}
public String read(String db, String table, String keycol, String key,
String... keyvals) {
try {
if (keyvals != null && keyvals.length == 2) {
String query = QueryFactory.BuildQuery(QueryType.SELECTEVENT,
StorageType.CASSANDRA);
return QueryUtils.formatQueryResult(
keyspace.prepareCqlStatement()
.withCql(
String.format(query, db + "." + table,
keycol, key, keyvals[0],
keyvals[1])).execute()
.getResult(), table);
} else {
String query = QueryFactory.BuildQuery(QueryType.SELECTALL,
StorageType.CASSANDRA);
OperationResult<CqlStatementResult> rs;
if (keycol != null && !keycol.equals("")) {
rs = keyspace
.prepareCqlStatement()
.withCql(
String.format(query, db + "." + table,
keycol, key)).execute();
} else {
rs = keyspace
.prepareCqlStatement()
.withCql(
String.format("select * from %s", db + "."
+ table)).execute();
}
if (rs != null)
return QueryUtils.formatQueryResult(rs.getResult(), table);
return "{\"msg\":\"Nothing is found\"}";
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public String createRowIndexTable(JsonObject payload) {
return null;
}
public void closeConnection() {
// TODO Auto-generated method stub
// No API exists for this in current implementation todo:investigate
}
}
| 652 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/CassandraConnection.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.staash.connection;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
import com.netflix.staash.common.query.QueryFactory;
import com.netflix.staash.common.query.QueryType;
import com.netflix.staash.common.query.QueryUtils;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.model.StorageType;
public class CassandraConnection implements PaasConnection {
private Cluster cluster;
private Session session;
public CassandraConnection(Cluster cluster) {
this.cluster = cluster;
session = this.cluster.connect();
}
public Session getSession() {
return cluster.connect();
}
public String insert(String db, String table, JsonObject payload) {
String query = QueryFactory.BuildQuery(QueryType.INSERT,
StorageType.CASSANDRA);
session.execute(String.format(query, db + "." + table,
payload.getString("columns"), payload.getValue("values")));
return "{\"message\":\"ok\"}";
}
public String createDB(String dbname) {
String sql = String.format(QueryFactory.BuildQuery(QueryType.CREATEDB,
StorageType.CASSANDRA), dbname, 1);
;
session.execute(sql);
return "{\"message\":\"ok\"}";
}
public String createTable(JsonObject payload) {
String sql = String
.format(QueryFactory.BuildQuery(QueryType.CREATETABLE,
StorageType.CASSANDRA), payload.getString("db") + "."
+ payload.getString("name"), QueryUtils.formatColumns(
payload.getString("columns"), StorageType.CASSANDRA),
payload.getString("primarykey"));
session.execute(sql + ";");
return "{\"message\":\"ok\"}";
}
public String read(String db, String table, String keycol, String key,
String... keyvals) {
if (keyvals != null && keyvals.length == 2) {
String query = QueryFactory.BuildQuery(QueryType.SELECTEVENT,
StorageType.CASSANDRA);
return QueryUtils.formatQueryResult(session.execute(String.format(
query, db + "." + table, keycol, key, keyvals[0],
keyvals[1])));
} else {
String query = QueryFactory.BuildQuery(QueryType.SELECT,
StorageType.CASSANDRA);
ResultSet rs = session.execute(String.format(query, db + "."
+ table, keycol, key));
if (rs != null && rs.all().size() > 0)
return QueryUtils.formatQueryResult(rs);
return "{\"msg\":\"Nothing is found\"}";
}
}
public void closeConnection() {
//Implement as per driver choice
}
public ByteArrayOutputStream readChunked(String db, String table, String objectName) {
return null;
}
public String writeChunked(String db, String table, String objectName,
InputStream is) {
return null;
}
}
| 653 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/MySqlConnection.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.staash.connection;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.netflix.staash.common.query.QueryFactory;
import com.netflix.staash.common.query.QueryType;
import com.netflix.staash.common.query.QueryUtils;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.model.StorageType;
public class MySqlConnection implements PaasConnection{
private Connection conn;
public MySqlConnection(Connection conn) {
this.conn = conn;
}
public Connection getConnection() {
return conn;
}
public String insert(String db, String table, JsonObject payload) {
String query = QueryFactory.BuildQuery(QueryType.INSERT, StorageType.MYSQL);
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate("USE "+db);
stmt.executeUpdate(String.format(query, table,payload.getString("columns"),payload.getValue("values")));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return "\"message\":\"ok\"";
}
public String createDB(String dbname) {
String sql = String.format(QueryFactory.BuildQuery(QueryType.CREATEDB, StorageType.MYSQL), dbname);;
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return "\"message\":\"ok\"";
}
public String createTable(JsonObject payload) {
Statement stmt = null;
String sql = String.format(QueryFactory.BuildQuery(QueryType.SWITCHDB, StorageType.MYSQL), payload.getString("db"));
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
String createTblQry = String.format(QueryFactory.BuildQuery(QueryType.CREATETABLE, StorageType.MYSQL), payload.getString("name"),QueryUtils.formatColumns(payload.getString("columns"),StorageType.MYSQL),payload.getString("primarykey"));
try {
stmt.executeUpdate(createTblQry);
} catch (SQLException e) {
}
return "\"message\":\"ok\"";
}
public String read(String db, String table, String keycol, String key, String... values) {
String query = QueryFactory.BuildQuery(QueryType.SELECTALL, StorageType.MYSQL);
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate("USE "+db);
ResultSet rs;
if (keycol!=null && !keycol.equals(""))
rs = stmt.executeQuery(String.format(query, table,keycol,key));
else
rs = stmt.executeQuery(String.format("select * from %s", table));
return QueryUtils.formatQueryResult(rs);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void closeConnection() {
if (conn!=null)
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
public ByteArrayOutputStream readChunked(String db, String table, String objectName) {
return null;
}
public String writeChunked(String db, String table, String objectName, InputStream is) {
return null;
}
}
| 654 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/GuiceConnectionFactory.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.staash.connection;
public class GuiceConnectionFactory {
}
| 655 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/PaasConnection.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.staash.connection;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import com.netflix.staash.json.JsonObject;
public interface PaasConnection {
public String insert(String db, String table, JsonObject payload);
public String read(String db, String table, String keycol, String key, String... keyvals);
public String createDB(String dbname);
public String createTable(JsonObject payload);
public void closeConnection();
public ByteArrayOutputStream readChunked(String db, String table, String objectName);
public String writeChunked(String db, String table, String objectName, InputStream is);
}
| 656 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/ConnectionFactory.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.staash.connection;
import com.netflix.staash.json.JsonObject;
public interface ConnectionFactory {
public PaasConnection createConnection(JsonObject storageConf, String db) ;
}
| 657 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/connection/PaasConnectionFactory.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.staash.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.policies.RoundRobinPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.netflix.staash.cassandra.discovery.EurekaAstyanaxHostSupplier;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.model.CassandraStorage;
import com.netflix.staash.model.MySqlStorage;
import com.netflix.staash.service.CLIENTTYPE;
public class PaasConnectionFactory implements ConnectionFactory{
private String clientType = "astyanax";
private EurekaAstyanaxHostSupplier hs;
public PaasConnectionFactory(String clientType, EurekaAstyanaxHostSupplier hs) {
this.clientType = clientType;
this.hs = hs;
}
public PaasConnection createConnection(JsonObject storageConf, String db) {
String type = storageConf.getString("type");
if (type.equals("mysql")) {
MySqlStorage mysqlStorageConf = new MySqlStorage(storageConf);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection(mysqlStorageConf.getJdbcurl(),mysqlStorageConf.getUser(), mysqlStorageConf.getPassword());
return new MySqlConnection(connection);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} else {
CassandraStorage cassStorage = new CassandraStorage(storageConf);
if (clientType.equals(CLIENTTYPE.ASTYANAX.getType())) {
return new AstyanaxCassandraConnection(cassStorage.getCluster(), db, hs);
} else {
Cluster cluster = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).addContactPoint(cassStorage.getCluster()).build();
return new CassandraConnection(cluster);
}
}
}
}
| 658 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/dao
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/dao/factory/DaoFactory.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.staash.dao.factory;
import com.netflix.staash.rest.dao.DataDao;
import com.netflix.staash.rest.dao.MetaDao;
public interface DaoFactory {
public DataDao getDataDao(String storage, String clientType);
public MetaDao getMetaDao();
}
| 659 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/dao
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/dao/factory/PaasDaoFactory.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.staash.dao.factory;
import java.util.HashMap;
import java.util.Map;
import com.datastax.driver.core.Cluster;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.netflix.staash.connection.ConnectionFactory;
import com.netflix.staash.rest.dao.AstyanaxDataDaoImpl;
import com.netflix.staash.rest.dao.CqlDataDaoImpl;
import com.netflix.staash.rest.dao.CqlMetaDaoImpl;
import com.netflix.staash.rest.dao.DataDao;
import com.netflix.staash.rest.dao.MetaDao;
public class PaasDaoFactory {
static Map<String, DataDao> DaoMap = new HashMap<String, DataDao>();
static String clientType = "cql";
public MetaDao metaDao;
public ConnectionFactory factory;
@Inject
public PaasDaoFactory(MetaDao metaDao, ConnectionFactory factory) {
this.metaDao = metaDao;
this.factory = factory;
}
public DataDao getDataDao(String storage, String clientType) {
String storageType = getStorageType(storage);
String cluster = getCluster(storage);
// String hostName = getHostName(cluster);
if (DaoMap.containsKey(cluster)) return DaoMap.get(cluster);
if (storageType.equals("cassandra") && clientType.equals("cql")) {
DataDao dataDao = DaoMap.get(cluster);
if (dataDao==null) {
// dataDao = new CqlDataDaoImpl(factory.getDataCluster(cluster),metaDao);
}
DaoMap.put(cluster, dataDao);
return dataDao;
} else if (storageType.equals("cassandra") && clientType.equals("astyanax")) {
DataDao dataDao = DaoMap.get(cluster);
if (dataDao==null) {
dataDao = new AstyanaxDataDaoImpl();//factory.getDataCluster(cluster),metaDao);
}
DaoMap.put(cluster, dataDao);
return dataDao;
} else if (storageType.equals("mysql") && clientType==null) {
}
return null;
}
public MetaDao getMetaDao() {
return metaDao;
}
private String getStorageType(String storage) {
return "cassandra";
}
private String getCluster(String storage) {
return "localhost";
}
private String getHostName(String cluster) {
//eureka name resolution
return "localhost";
}
}
| 660 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/storage
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/storage/service/MongoDBService.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.staash.storage.service;
public class MongoDBService {
}
| 661 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/storage
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/storage/service/MySqlService.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.staash.storage.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySqlService {
public static void createDbInMySql(String dbName) {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
Statement stmt = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/","root", "");
String sql = "CREATE DATABASE "+dbName;
stmt = connection.createStatement();
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
}
public static void createTableInDb(String schema, String query) {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+schema,"root", "");
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database...");
Statement stmt = conn.createStatement();
// String sql = "CREATE TABLE REGISTRATION " +
// "(id INTEGER not NULL, " +
// " first VARCHAR(255), " +
// " last VARCHAR(255), " +
// " age INTEGER, " +
// " PRIMARY KEY ( id ))";
stmt.executeUpdate(query);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void insertRowIntoTable(String db, String table, String query) {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db,"root", "");
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database...");
Statement stmt = conn.createStatement();
// String sql = "CREATE TABLE REGISTRATION " +
// "(id INTEGER not NULL, " +
// " first VARCHAR(255), " +
// " last VARCHAR(255), " +
// " age INTEGER, " +
// " PRIMARY KEY ( id ))";
stmt.executeUpdate(query);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static ResultSet executeRead(String db, String query) {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db,"root", "");
Statement stmt = conn.createStatement();
return stmt.executeQuery(query);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| 662 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/storage
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/storage/service/HTableService.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.staash.storage.service;
public class HTableService {
}
| 663 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common/query/QueryUtils.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.staash.common.query;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.lang.RuntimeException;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.Row;
import com.netflix.astyanax.cql.CqlStatementResult;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Rows;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.model.StorageType;
public class QueryUtils {
public static String formatColumns(String columnswithtypes, StorageType stype) {
// TODO Auto-generated method stub
String[] allCols = columnswithtypes.split(",");
String outputCols = "";
for (String col:allCols) {
String type;
String name;
if (!col.contains(":")) {
if (stype!=null && stype.getCannonicalName().equals(StorageType.MYSQL.getCannonicalName())) type = "varchar(256)";
else type="text";
name=col;
}
else {
name = col.split(":")[0];
type = col.split(":")[1];
}
outputCols = outputCols + name + " " + type +",";
}
return outputCols;
}
public static String formatQueryResult(ResultSet rs) {
try {
JsonObject fullResponse = new JsonObject();
int rcount = 1;
while (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
String columns ="";
String values = "";
int count = rsmd.getColumnCount();
for (int i=1;i<=count;i++) {
String colName = rsmd.getColumnName(i);
columns = columns + colName + ",";
String value = rs.getString(i);
values = values + value +",";
}
JsonObject response = new JsonObject();
response.putString("columns", columns.substring(0, columns.length()-1));
response.putString("values", values.substring(0, values.length()-1));
fullResponse.putObject("row"+rcount++, response);
}
return fullResponse.toString();
} catch (SQLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
throw new RuntimeException(e);
}
}
public static String formatQueryResult(com.datastax.driver.core.ResultSet rs) {
// TODO Auto-generated method stub
String colStr = "";
String rowStr = "";
JsonObject response = new JsonObject();
List<Row> rows = rs.all();
if (!rows.isEmpty() && rows.size() == 1) {
rowStr = rows.get(0).toString();
}
ColumnDefinitions colDefs = rs.getColumnDefinitions();
colStr = colDefs.toString();
response.putString("columns", colStr.substring(8, colStr.length() - 1));
response.putString("values", rowStr.substring(4, rowStr.length() - 1));
return response.toString();
}
public static String formatQueryResult(CqlStatementResult rs, String cfname) {
// TODO Auto-generated method stub
String value = "";
JsonObject response = new JsonObject();
ColumnFamily<String, String> cf = ColumnFamily
.newColumnFamily(cfname, StringSerializer.get(),
StringSerializer.get());
Rows<String, String> rows = rs.getRows(cf);
int rcount = 1;
for (com.netflix.astyanax.model.Row<String, String> row : rows) {
ColumnList<String> columns = row.getColumns();
Collection<String> colnames = columns.getColumnNames();
String rowStr = "";
String colStr = "";
if (colnames.contains("key") && colnames.contains("column1")) {
colStr = colStr + columns.getDateValue("column1", null).toGMTString();
rowStr = rowStr + columns.getStringValue("value", null);
response.putString(colStr, rowStr);
} else {
JsonObject rowObj = new JsonObject();
for (String colName:colnames) {
//colStr = colStr+colname+",";
value = columns.getStringValue(colName, null);
//rowStr=rowStr+value+",";
rowObj.putString(colName, value);
}
//rowobj.putString("columns", colStr);
//rowobj.putString("values", rowStr);
response.putObject(""+rcount++, rowObj);
}
}
return response.toString();
}
}
| 664 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common/query/QueryType.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.staash.common.query;
public enum QueryType {
REPLACE, INSERT, SELECT, UPDATE, DELETE, ALTER, UNCLASSIFIABLE,CREATEDB,CREATETABLE,CREATESERIES,SWITCHDB,SELECTALL,SELECTEVENT;
public static QueryType classifyQuery(final String query) {
final String lowerCaseQuery = query.toLowerCase();
if (lowerCaseQuery.startsWith("select")) {
return QueryType.SELECT;
} else if (lowerCaseQuery.startsWith("update")) {
return QueryType.UPDATE;
} else if (lowerCaseQuery.startsWith("insert")) {
return QueryType.INSERT;
} else if (lowerCaseQuery.startsWith("alter")) {
return QueryType.ALTER;
} else if (lowerCaseQuery.startsWith("delete")) {
return QueryType.DELETE;
} else if (lowerCaseQuery.startsWith("replace")) {
return QueryType.REPLACE;
} else if (lowerCaseQuery.startsWith("createdb")) {
return QueryType.CREATEDB;
} else if (lowerCaseQuery.startsWith("createtable")) {
return QueryType.CREATETABLE;
} else if (lowerCaseQuery.startsWith("switchdb")) {
return QueryType.SWITCHDB;
} else if (lowerCaseQuery.startsWith("selectall")) {
return QueryType.SELECTALL;
} else if (lowerCaseQuery.startsWith("createseries")) {
return QueryType.CREATESERIES;
} else if (lowerCaseQuery.startsWith("selectevent")) {
return QueryType.SELECTEVENT;
} else {
return QueryType.UNCLASSIFIABLE;
}
}
}
| 665 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common/query/QueryFactory.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.staash.common.query;
import com.netflix.staash.model.StorageType;
public class QueryFactory {
public static final String INSERT_FORMAT = "INSERT INTO %s(%s) VALUES (%s)";
public static final String CREATE_DB_FORMAT_MYSQL = "CREATE DATABASE %s";
public static final String CREATE_DB_FORMAT_CASS = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }";
public static final String CREATE_TABLE_FORMAT = "CREATE TABLE %s(%s PRIMARY KEY(%s))";
public static final String SWITCH_DB_FORMAT = "USE %s";
public static final String SELECT_ALL = "SELECT * FROM %s WHERE %s='%s';";
public static final String SELECT_EVENT = "SELECT * FROM %s WHERE %s='%s' AND %s=%s;";
public static String BuildQuery(QueryType qType,StorageType sType) {
switch (sType) {
case CASSANDRA:
switch (qType) {
case INSERT:
return INSERT_FORMAT;
case CREATEDB:
return CREATE_DB_FORMAT_CASS;
case CREATETABLE:
return CREATE_TABLE_FORMAT;
case SWITCHDB:
return SWITCH_DB_FORMAT;
case SELECTALL:
return SELECT_ALL;
case SELECTEVENT:
return SELECT_EVENT;
}
case MYSQL:
switch (qType) {
case INSERT:
return INSERT_FORMAT;
case CREATEDB:
return CREATE_DB_FORMAT_MYSQL;
case CREATETABLE:
return CREATE_TABLE_FORMAT;
case SWITCHDB:
return SWITCH_DB_FORMAT;
case SELECTALL:
return SELECT_ALL;
}
}
return null;
}
// //needs to be modified
// public static String BuildCreateTableQuery(PaasTableEntity tableEnt, StorageType type) {
// // TODO Auto-generated method stub
// String storage = tableEnt.getStorage();
// if (type!=null && type.getCannonicalName().equals(StorageType.MYSQL.getCannonicalName())) {
// String schema = tableEnt.getSchemaName();
// String tableName = tableEnt.getName().split("\\.")[1];
// List<Pair<String, String>> columns = tableEnt.getColumns();
// String colStrs = "";
// for (Pair<String, String> colPair : columns) {
// colStrs = colStrs + colPair.getRight() + " " + colPair.getLeft()
// + ", ";
// }
// String primarykeys = tableEnt.getPrimarykey();
// String PRIMARYSTR = "PRIMARY KEY(" + primarykeys + ")";
// return "CREATE TABLE " + tableName + " (" + colStrs
// + " " + PRIMARYSTR + ");";
// } else {
// String schema = tableEnt.getSchemaName();
// String tableName = tableEnt.getName().split("\\.")[1];
// List<Pair<String, String>> columns = tableEnt.getColumns();
// String colStrs = "";
// for (Pair<String, String> colPair : columns) {
// colStrs = colStrs + colPair.getRight() + " " + colPair.getLeft()
// + ", ";
// }
// String primarykeys = tableEnt.getPrimarykey();
// String PRIMARYSTR = "PRIMARY KEY(" + primarykeys + ")";
// return "CREATE TABLE " + schema + "." + tableName + " (" + colStrs
// + " " + PRIMARYSTR + ");";
// }
// }
}
| 666 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common/query/Query.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.staash.common.query;
import java.io.IOException;
import java.io.OutputStream;
public interface Query {
int length() throws QueryException;
void writeTo(OutputStream os) throws IOException, QueryException;
String getQuery();
QueryType getQueryType();
void writeTo(OutputStream ostream, int offset, int packLength) throws IOException, QueryException;
}
| 667 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/common/query/QueryException.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.staash.common.query;
public class QueryException extends Exception {
private final int errorCode;
private final String sqlState;
public QueryException(final String message) {
super(message);
this.errorCode = -1;
this.sqlState = "HY0000";
}
public QueryException(final String message, final short errorCode,
final String sqlState) {
super(message);
this.errorCode = errorCode;
this.sqlState = sqlState;
}
public QueryException(final String message, final int errorCode,
final String sqlState, final Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
this.sqlState = sqlState;
}
public final int getErrorCode() {
return errorCode;
}
public final String getSqlState() {
return sqlState;
}
}
| 668 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/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.staash.json;
import java.util.*;
import com.netflix.staash.json.impl.Base64;
import com.netflix.staash.json.impl.Json;
import java.lang.Iterable;
/**
* 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));
}
public Iterator<Object> iterator() {
return new Iterator<Object>() {
Iterator<Object> iter = list.iterator();
public boolean hasNext() {
return iter.hasNext();
}
public Object next() {
return convertObject(iter.next());
}
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;
}
}
| 669 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/json/JsonElement.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.staash.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;
}
}
| 670 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/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.staash.json;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.netflix.staash.json.impl.Base64;
import com.netflix.staash.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;
}
}
| 671 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/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.staash.json;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class EncodeException extends RuntimeException {
public EncodeException(String message) {
super(message);
}
public EncodeException() {
}
}
| 672 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/json/PaasJson.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.staash.json;
public class PaasJson {
public static final String CASS_STORAGE = new JsonObject().putString("name", "name")
.putString("type", "cassandra")
.putString("cluster", "cluster")
.putString("port", "port")
.putString("replicationfactor", "3")
.putString("strategy", "NetworkTopologyStrategy")
.putString("asyncreplicate", "")
.putString("poolsize", "3")
.toString();
public static final String MYSQL_STORAGE = new JsonObject().putString("name", "name")
.putString("type", "mysql")
.putString("host", "host")
.putString("jdbcurl", "jdbc:mysql://localhost:3306/")
.putString("user", "user")
.putString("port", "port")
.putString("asyncreplicate", "")
.toString();
public static final String PASS_DB = new JsonObject().putString("name", "name").toString();
public static final String PASS_TABLE = new JsonObject().putString("name","name")
.putString("columns", "column1,column2")
.putString("storage", "storagename")
.putString("indexrowkeys", "true")
.toString();
public static final String PASS_TIMESERIES = new JsonObject().putString("name", "name")
.putString("periodicity", "milliseconds")
.putString("prefix", "yesorno")
.toString();
public static final String TABLE_INSERT_ROW = new JsonObject().putString("columns", "col1,col2,col3")
.putString("values", "value1,value2,value3")
.toString();
public static final String TS_INSERT_EVENT = new JsonObject().putString("time", "milliseconds")
.putString("event", "event payload")
.putString("prefix", "prefix")
.toString();
public static final String READ_EVENT_URL = "http://hostname:8080/paas/v1/data/time/100000";
public static final String READ_ROW_URL = "http://hostname:8080/paas/v1/data";
public static final String LIST_SCHEMAS_URL = "http://hostname:8080/paas/v1/admin";
public static final String LIST_STORAGE_URL = "http://hostname:8080/paas/v1/admin/storage";
public static final String LIST_TABLES_URL = "http://hostname:8080/paas/v1/admin/db";
public static final String CREATE_DB_URL = "http://hostname:8080/paas/v1/admin";
public static final String CREATE_TABLE_URL = "http://hostname:8080/paas/v1/admin/db";
public static final String CREATE_TS_URL = "http://hostname:8080/paas/v1/admin/db/timeseries";
public static final String CREATE_STORAGE_URL = "http://hostname:8080/paas/v1/admin/storage";
public static final String LIST_TS_URL = "http://hostname:8080/paas/v1/admin/db/timeseries";
public static final String INSERT_EVENT_URL = "http://hostname:8080/paas/v1/data/db/timeseries";
public static final String WRITE_ROW_URL = "http://hostname:8080/paas/v1/data/db/table";
}
| 673 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/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.staash.json;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class DecodeException extends RuntimeException {
public DecodeException() {
}
public DecodeException(String message) {
super(message);
}
}
| 674 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/json
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/json/impl/Base64.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.staash.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
| 675 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/json
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/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.staash.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.staash.json.DecodeException;
import com.netflix.staash.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);
}
}
| 676 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/cassandra
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/cassandra/discovery/HostSupplierProvider.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.staash.cassandra.discovery;
import java.util.List;
import com.google.common.base.Supplier;
import com.netflix.astyanax.connectionpool.Host;
public interface HostSupplierProvider {
public Supplier<List<Host>> getSupplier(String clusterName);
}
| 677 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/cassandra
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/cassandra/discovery/EurekaModule.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.staash.cassandra.discovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.MapBinder;
import com.netflix.appinfo.CloudInstanceConfig;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryManager;
public class EurekaModule extends AbstractModule {
private static final Logger LOG = LoggerFactory.getLogger(EurekaModule.class);
@Override
protected void configure() {
LOG.info("Configuring EurekaModule");
DiscoveryManager.getInstance().initComponent(
new CloudInstanceConfig(),
new DefaultEurekaClientConfig());
// Eureka - Astyanax integration
MapBinder<String, HostSupplierProvider> hostSuppliers = MapBinder.newMapBinder(binder(), String.class, HostSupplierProvider.class);
hostSuppliers.addBinding("eureka").to(EurekaAstyanaxHostSupplier.class).asEagerSingleton();
//bind(ClusterDiscoveryService.class).to(EurekaClusterDiscoveryService.class).asEagerSingleton();
}
}
| 678 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/cassandra
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/cassandra/discovery/EurekaAstyanaxHostSupplier.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.staash.cassandra.discovery;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.AmazonInfo.MetaDataKey;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.DiscoveryManager;
import com.netflix.discovery.shared.Application;
public class EurekaAstyanaxHostSupplier implements HostSupplierProvider {
private static final Logger LOG = LoggerFactory.getLogger(EurekaAstyanaxHostSupplier.class);
private final DiscoveryClient eurekaClient;
public EurekaAstyanaxHostSupplier() {
this.eurekaClient = DiscoveryManager.getInstance().getDiscoveryClient();
Preconditions.checkNotNull(this.eurekaClient);
}
public Supplier<List<Host>> getSupplier(final String clusterName) {
return new Supplier<List<Host>>() {
public List<Host> get() {
Application app = eurekaClient.getApplication(clusterName.toUpperCase());
List<Host> hosts = Lists.newArrayList();
if (app == null) {
LOG.warn("Cluster '{}' not found in eureka", new Object[]{clusterName});
}
else {
List<InstanceInfo> ins = app.getInstances();
if (ins != null && !ins.isEmpty()) {
hosts = Lists.newArrayList(Collections2.transform(
Collections2.filter(ins, new Predicate<InstanceInfo>() {
public boolean apply(InstanceInfo input) {
return input.getStatus() == InstanceInfo.InstanceStatus.UP;
}
}), new Function<InstanceInfo, Host>() {
public Host apply(InstanceInfo info) {
String[] parts = StringUtils.split(
StringUtils.split(info.getHostName(), ".")[0], '-');
Host host = new Host(info.getHostName(), info.getPort())
.addAlternateIpAddress(
StringUtils.join(new String[] { parts[1], parts[2], parts[3],
parts[4] }, "."))
.addAlternateIpAddress(info.getIPAddr())
.setId(info.getId());
try {
if (info.getDataCenterInfo() instanceof AmazonInfo) {
AmazonInfo amazonInfo = (AmazonInfo)info.getDataCenterInfo();
host.setRack(amazonInfo.get(MetaDataKey.availabilityZone));
}
}
catch (Throwable t) {
LOG.error("Error getting rack for host " + host.getName(), t);
}
return host;
}
}));
}
else {
LOG.warn("Cluster '{}' found in eureka but has no instances", new Object[]{clusterName});
}
}
return hosts;
}
};
}
}
| 679 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/model/Storage.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.staash.model;
public class Storage {
String name;
StorageType type;
String replicateTo;
}
| 680 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/model/StorageType.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.staash.model;
public enum StorageType {
CASSANDRA("cassandra"),MYSQL("mysql");
private String cannonicalName;
StorageType(String cannonicalName) {
this.cannonicalName = cannonicalName;
}
public String getCannonicalName() {
return cannonicalName;
}
}
| 681 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/model/MySqlStorage.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.staash.model;
import com.netflix.staash.json.JsonObject;
public class MySqlStorage extends Storage{
private String jdbcurl;
private String user;
private String password;
private String host;
public MySqlStorage(JsonObject conf) {
this.host = conf.getString("host");
this.jdbcurl = conf.getString("jdbcurl");
this.name = conf.getString("name");
this.user = conf.getString("user");
this.password = conf.getString("password");
}
public String getJdbcurl() {
return jdbcurl;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
public String getHost() {
return host;
}
}
| 682 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/model/CassandraStorage.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.staash.model;
import com.netflix.staash.json.JsonObject;
public class CassandraStorage extends Storage{
private String cluster;
public CassandraStorage(JsonObject conf) {
this.name = conf.getString("name");
this.cluster = conf.getString("cluster");
this.replicateTo = conf.getString("replicateto");
this.type = StorageType.CASSANDRA;
}
public String getName() {
return name;
}
public String getCluster() {
return cluster;
}
public StorageType getType() {
return type;
}
public String getReplicateTo() {
return replicateTo;
}
}
| 683 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/service/DataService.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.staash.service;
import java.io.InputStream;
import com.netflix.staash.json.JsonArray;
import com.netflix.staash.json.JsonObject;
public interface DataService {
public String writeRow(String db, String table, JsonObject rowObj);
public String listRow(String db, String table, String keycol, String key);
public String writeEvent(String db, String table, JsonObject rowObj);
public String writeEvents(String db, String table, JsonArray rowObj);
public String readEvent(String db, String table, String eventTime);
public String readEvent(String db, String table, String prefix,String eventTime);
public String readEvent(String db, String table, String prefix,String startTime, String endTime);
public String doJoin(String db, String table1, String table2,
String joincol, String value);
public String writeToKVStore(String db, String table, JsonObject obj);
public byte[] fetchValueForKey(String db, String table,
String keycol, String key);
public byte[] readChunked(String db, String table, String objectName);
public String writeChunked(String db, String table, String objectName, InputStream is);
}
| 684 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/service/MetaService.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.staash.service;
import java.util.Map;
import com.netflix.staash.exception.PaasException;
import com.netflix.staash.exception.StorageDoesNotExistException;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.rest.dao.DataDao;
import com.netflix.staash.rest.dao.MetaDao;
import com.netflix.staash.rest.meta.entity.Entity;
import com.netflix.staash.rest.meta.entity.EntityType;
public interface MetaService {
public String writeMetaEntity(EntityType etype, String entity) throws StorageDoesNotExistException;
// public Entity readMetaEntity(String rowKey);
// public String writeRow(String db, String table, JsonObject rowObj);
// public String listRow(String db, String table, String keycol, String key);
public String listSchemas();
public String listTablesInSchema(String schemaname);
public String listTimeseriesInSchema(String schemaname);
public String listStorage();
public Map<String,String> getStorageMap();
public String CreateDB();
public String createTable();
public JsonObject runQuery(EntityType etype, String col);
public JsonObject getStorageForTable(String table);
}
| 685 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/service/CacheService.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.staash.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.staash.json.JsonArray;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.rest.dao.MetaDao;
import com.netflix.staash.rest.meta.entity.Entity;
import com.netflix.staash.rest.meta.entity.EntityType;
import com.netflix.staash.rest.util.MetaConstants;
public class CacheService {
List<String> dbHolder = new ArrayList<String>();
Map<String, String> tableToStorageMap = new ConcurrentHashMap<String, String>();
Map<String, JsonObject> storageMap = new ConcurrentHashMap<String, JsonObject>();
Map<String, List<String>> dbToTableMap = new ConcurrentHashMap<String, List<String>>();
Map<String, List<String>> dbToTimeseriesMap = new ConcurrentHashMap<String, List<String>>();
private MetaDao meta;
public CacheService(MetaDao meta) {
this.meta = meta;
// LoadStorage();
// LoadDbNames();
// LoadTableMaps();
// LoadDbToTimeSeriesMap();
}
private void LoadTableMaps() {
Map<String, JsonObject> tblmap = meta.runQuery(
MetaConstants.STAASH_TABLE_ENTITY_TYPE, "*");
for (String tableName : tblmap.keySet()) {
JsonObject tblPay = tblmap.get(tableName);
String storage = tblPay.getString("storage");
tableToStorageMap.put(tableName, storage);
String key = tableName.split("\\.")[0];
String table = tableName.split("\\.")[1];
List<String> currval = null;
currval = dbToTableMap.get(key);
if (currval == null) {
currval = new ArrayList<String>();
}
currval.add(table);
dbToTableMap.put(key, currval);
}
}
public void LoadStorage() {
storageMap = meta.runQuery(MetaConstants.STAASH_STORAGE_TYPE_ENTITY, "*");
}
private void LoadDbNames() {
Map<String, JsonObject> dbmap = meta.runQuery(
MetaConstants.STAASH_DB_ENTITY_TYPE, "*");
for (String key : dbmap.keySet()) {
dbHolder.add(key);
}
}
private void LoadDbToTimeSeriesMap() {
Map<String, JsonObject> tblmap = meta.runQuery(
MetaConstants.STAASH_TS_ENTITY_TYPE, "*");
for (String tableName : tblmap.keySet()) {
JsonObject tblPay = tblmap.get(tableName);
String storage = tblPay.getString("storage");
if (storage != null && storage.length() > 0)
tableToStorageMap.put(tableName, storage);
String key = tableName.split("\\.")[0];
String table = tableName.split("\\.")[1];
List<String> currval = null;
currval = dbToTimeseriesMap.get(key);
if (currval == null) {
currval = new ArrayList<String>();
}
currval.add(table);
dbToTimeseriesMap.put(key, currval);
}
}
// public void updateMaps(EntityType etype, JsonObject obj) {
// switch (etype) {
// case STORAGE:
// storageMap.put(obj.getString("name"), obj);
// break;
// case DB:
// String dbname = obj.getString("name");
// dbHolder.add(dbname);
// break;
// case TABLE:
// String tblname = obj.getString("name");
// List<String> currval = dbToTableMap.get(tblname);
// if (currval == null) {
// currval = new ArrayList<String>();
// }
// currval.add(tblname);
// dbToTableMap.put(tblname, currval);
// String storage = obj.getString("storage");
// tableToStorageMap.put(tblname, storage);
// break;
// case SERIES:
// String seriesname = obj.getString("name");
// List<String> currseries = dbToTimeseriesMap.get(seriesname);
// if (currseries == null) {
// currseries = new ArrayList<String>();
// }
// currseries.add(seriesname);
// dbToTimeseriesMap.put(seriesname, currseries);
// String tsstorage = obj.getString("storage");
// tableToStorageMap.put(seriesname, tsstorage);
// break;
// }
// }
public boolean checkUniqueDbName(String dbName) {
// return dbHolder.contains(dbName);
Map<String,JsonObject> names = meta.runQuery(MetaConstants.STAASH_DB_ENTITY_TYPE, dbName);
if (names!=null && !names.isEmpty())
return names.containsKey(dbName);
else
return false;
}
public List<String> getDbNames() {
// return dbHolder;
Map<String,JsonObject> dbmap = meta.runQuery(MetaConstants.STAASH_DB_ENTITY_TYPE, "*");
List<String> dbNames = new ArrayList<String>();
for (String key : dbmap.keySet()) {
dbNames.add(key);
}
return dbNames;
}
public List<String> getTableNames(String db) {
Map<String, JsonObject> tblmap = meta.runQuery(
MetaConstants.STAASH_TABLE_ENTITY_TYPE, "*");
List<String> tableNames = new ArrayList<String>();
for (String tableName : tblmap.keySet()) {
if (tableName.startsWith(db+".")) {
String table = tableName.split("\\.")[1];
tableNames.add(table);
}
}
return tableNames;
}
public Set<String> getStorageNames() {
// return storageMap.keySet();
Map<String, JsonObject> storages = meta.runQuery(MetaConstants.STAASH_STORAGE_TYPE_ENTITY, "*");
if (storages != null)
return storages.keySet();
else
return Collections.emptySet();
}
public JsonObject getStorage(String storage) {
// return storageMap.get(storage);
Map<String, JsonObject> storages = meta.runQuery(MetaConstants.STAASH_STORAGE_TYPE_ENTITY, "*");
if (storages != null)
return storages.get(storage);
else
return null;
}
public List<String> getSeriesNames(String db) {
// return dbToTimeseriesMap.get(db);
Map<String, JsonObject> tblmap = meta.runQuery(
MetaConstants.STAASH_TS_ENTITY_TYPE, "*");
List<String> tableNames = new ArrayList<String>();
for (String tableName : tblmap.keySet()) {
if (tableName.startsWith(db+".")) {
String table = tableName.split("\\.")[1];
tableNames.add(table);
}
}
return tableNames;
}
public void addEntityToCache(EntityType etype, Entity entity) {
// switch (etype) {
// case STORAGE:
// storageMap.put(entity.getName(),
// new JsonObject(entity.getPayLoad()));
// break;
// case DB:
// dbHolder.add(entity.getName());
// break;
// case TABLE:
// JsonObject payobject = new JsonObject(entity.getPayLoad());
// tableToStorageMap.put(entity.getName(),
// payobject.getString("storage"));
// String db = payobject.getString("db");
// List<String> tables = dbToTableMap.get(db);
// if (tables == null || tables.size() == 0) {
// tables = new ArrayList<String>();
// tables.add(payobject.getString("name"));
// } else {
// tables.add(payobject.getString("name"));
// }
// dbToTableMap.put(db, tables);
// break;
//
// case SERIES:
// JsonObject tsobject = new JsonObject(entity.getPayLoad());
// tableToStorageMap.put(entity.getName(),
// tsobject.getString("storage"));
// String dbname = tsobject.getString("db");
// List<String> alltables = dbToTableMap.get(dbname);
// if (alltables == null || alltables.size() == 0) {
// alltables = new ArrayList<String>();
// alltables.add(entity.getName());
// } else {
// alltables.add(entity.getName());
// }
// dbToTimeseriesMap.put(dbname, alltables);
// break;
// }
}
public JsonObject getStorageForTable(String tableParam) {
Map<String, JsonObject> tblmap = meta.runQuery(
MetaConstants.STAASH_TABLE_ENTITY_TYPE, "*");
List<String> tableNames = new ArrayList<String>();
for (String tableName : tblmap.keySet()) {
if (tableName.equals(tableParam)) {
JsonObject tblPayload = tblmap.get(tableParam);
String storage = tblPayload.getString("storage");
return getStorage(storage);
}
}
tblmap = meta.runQuery(
MetaConstants.STAASH_TS_ENTITY_TYPE, "*");
tableNames = new ArrayList<String>();
for (String tableName : tblmap.keySet()) {
if (tableName.equals(tableParam)) {
JsonObject tblPayload = tblmap.get(tableParam);
String storage = tblPayload.getString("storage");
return getStorage(storage);
}
}
return null;
// String storage = tableToStorageMap.get(table);
// JsonObject storageConf = storageMap.get(storage);
// return storageConf;
}
public String listStorage() {
// Set<String> allStorage = storageMap.keySet();
Set<String> allStorage = getStorageNames();
JsonObject obj = new JsonObject();
JsonArray arr = new JsonArray();
for (String storage : allStorage) {
arr.addString(storage);
}
obj.putArray("storages", arr);
return obj.toString();
}
public String listSchemas() {
JsonObject obj = new JsonObject();
JsonArray arr = new JsonArray();
List<String> allDbNames = getDbNames();
for (String db : allDbNames) {
arr.addString(db);
}
obj.putArray("schemas", arr);
return obj.toString();
}
public String listTablesInSchema(String db) {
List<String> tables = getTableNames(db);
JsonObject obj = new JsonObject();
JsonArray arr = new JsonArray();
for (String table : tables) {
arr.addString(table);
}
obj.putArray(db, arr);
return obj.toString();
}
public String listTimeseriesInSchema(String db) {
List<String> tables = getSeriesNames(db);
JsonObject obj = new JsonObject();
JsonArray arr = new JsonArray();
obj.putArray(db, arr);
if (tables != null) {
for (String table : tables) {
arr.addString(table);
}
obj.putArray(db, arr);
}
return obj.toString();
}
}
| 686 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/service/PaasMetaService.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.staash.service;
import java.util.Map;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.netflix.staash.connection.ConnectionFactory;
import com.netflix.staash.connection.PaasConnection;
import com.netflix.staash.exception.StorageDoesNotExistException;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.rest.dao.MetaDao;
import com.netflix.staash.rest.meta.entity.EntityType;
import com.netflix.staash.rest.meta.entity.PaasDBEntity;
import com.netflix.staash.rest.meta.entity.PaasStorageEntity;
import com.netflix.staash.rest.meta.entity.PaasTableEntity;
import com.netflix.staash.rest.meta.entity.PaasTimeseriesEntity;
public class PaasMetaService implements MetaService {
private MetaDao meta;
private ConnectionFactory cfactory;
private CacheService cache;
@Inject
public PaasMetaService(@Named("newmetadao") MetaDao meta, ConnectionFactory fac, CacheService cache) {
this.meta = meta;
// this.cfactory = new PaasConnectionFactory(CLIENTTYPE.ASTYANAX.getType());
this.cfactory = fac;
// this.cache = new CacheService(meta);
this.cache = cache;
}
public String writeMetaEntity(EntityType etype, String payload) throws StorageDoesNotExistException{
// TODO Auto-generated method stub
if (payload != null) {
switch (etype) {
case STORAGE:
PaasStorageEntity pse = PaasStorageEntity.builder()
.withJsonPayLoad(new JsonObject(payload)).build();
String retsto = meta.writeMetaEntity(pse);
cache.addEntityToCache(EntityType.STORAGE, pse);
return retsto;
case DB:
PaasDBEntity pdbe = PaasDBEntity.builder()
.withJsonPayLoad(new JsonObject(payload)).build();
String retdb = meta.writeMetaEntity(pdbe);
cache.addEntityToCache(EntityType.DB, pdbe);
return retdb;
case TABLE:
String schema = new JsonObject(payload).getString("db");
PaasTableEntity pte = PaasTableEntity.builder()
.withJsonPayLoad(new JsonObject(payload), schema)
.build();
createDBTable(pte.getPayLoad());
String rettbl = meta.writeMetaEntity(pte);
cache.addEntityToCache(EntityType.TABLE, pte);
return rettbl;
case SERIES:
String tsschema = new JsonObject(payload).getString("db");
PaasTimeseriesEntity ptse = PaasTimeseriesEntity.builder()
.withJsonPayLoad(new JsonObject(payload), tsschema)
.build();
createDBTable(ptse.getPayLoad());
String retseries = meta.writeMetaEntity(ptse);
cache.addEntityToCache(EntityType.SERIES, ptse);
return retseries;
}
}
return null;
}
private void createDBTable(String payload ) throws StorageDoesNotExistException {
// String payload = pte.getPayLoad();
JsonObject obj = new JsonObject(payload);
String schema = obj.getString("db");
String storage = obj.getString("storage");
String index_row_keys = obj.getString("indexrowkeys");
Map<String, JsonObject> sMap = meta.runQuery(
EntityType.STORAGE.getId(), storage);
JsonObject storageConfig = sMap.get(storage);
String strategy = storageConfig.getString("strategy");
String rf = storageConfig.getString("rf");
if (strategy==null || strategy.equals("") || strategy.equalsIgnoreCase("network")) strategy = "NetworkTopologyStrategy";
if (rf==null || rf.equals("")) rf = "us-east:3";
Map<String,JsonObject> dbMap = meta.runQuery(EntityType.DB.getId(), schema);
JsonObject dbConfig = dbMap.get(schema);
if (dbConfig.getString("strategy")==null || dbConfig.getString("strategy").equals("") || dbConfig.getString("rf")==null || dbConfig.getString("rf").equals(""))
{
dbConfig.putString("strategy", strategy);
dbConfig.putString("rf", rf);
}
if (storageConfig == null) throw new StorageDoesNotExistException();
PaasConnection conn = cfactory.createConnection(storageConfig, schema);
try {
if (storageConfig.getString("type").equals("mysql"))
conn.createDB(dbConfig.getString("name"));
else
conn.createDB(dbConfig.toString());
} catch (Exception e) {
// TODO: handle exception
}
try {
conn.createTable(obj);
if (index_row_keys!=null && index_row_keys.equals("true")) {
JsonObject idxObj = new JsonObject();
idxObj.putString("db", schema);
idxObj.putString("name", obj.getString("name")+"ROWKEYS");
idxObj.putString("columns", "key,column1,value");
idxObj.putString("primarykey", "key,column1");
conn.createTable(idxObj);
//conn.createRowIndexTable(obj)
}
} catch (Exception e) {
// TODO: handle exception
}
}
// public Entity readMetaEntity(String rowKey) {
// // TODO Auto-generated method stub
// return meta.readMetaEntity(rowKey);
// }
//
// public String writeRow(String db, String table, JsonObject rowObj) {
// // TODO Auto-generated method stub
// return meta.writeRow(db, table, rowObj);
// }
//
// public String listRow(String db, String table, String keycol, String key) {
// // TODO Auto-generated method stub
// return meta.listRow(db, table, keycol, key);
// }
public String listSchemas() {
// TODO Auto-generated method stub
return cache.listSchemas();
}
public String listTablesInSchema(String schemaname) {
// TODO Auto-generated method stub
return cache.listTablesInSchema(schemaname);
}
public String listTimeseriesInSchema(String schemaname) {
// TODO Auto-generated method stub
return cache.listTimeseriesInSchema(schemaname);
}
public String listStorage() {
// TODO Auto-generated method stub
return cache.listStorage();
}
public Map<String, String> getStorageMap() {
// TODO Auto-generated method stub
return null;
}
public String CreateDB() {
// TODO Auto-generated method stub
return null;
}
public String createTable() {
// TODO Auto-generated method stub
return null;
}
public JsonObject getStorageForTable(String table) {
return cache.getStorageForTable(table);
}
public JsonObject runQuery(EntityType etype, String col) {
return meta.runQuery(etype.getId(), col).get(col);
}
}
| 687 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/service/PaasDataService.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.staash.service;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.Executors;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Inject;
import com.netflix.staash.connection.ConnectionFactory;
import com.netflix.staash.connection.PaasConnection;
import com.netflix.staash.json.JsonArray;
import com.netflix.staash.json.JsonObject;
import com.netflix.staash.rest.meta.entity.EntityType;
public class PaasDataService implements DataService{
private MetaService meta;
private ConnectionFactory fac;
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
@Inject
public PaasDataService(MetaService meta, ConnectionFactory fac){
this.meta = meta;
this.fac = fac;
}
public String writeRow(String db, String table, JsonObject rowObj) {
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
PaasConnection conn = fac.createConnection(storageConf, db);
return conn.insert(db,table,rowObj);
}
public String writeToKVStore(String db, String table, JsonObject rowObj) {
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
PaasConnection conn = fac.createConnection(storageConf, db);
rowObj.putString("type", "kv");
return conn.insert(db, table, rowObj);
}
public String listRow(String db, String table, String keycol, String key) {
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) return "{\"msg\":\"the requested table does not exist in paas\"}";
PaasConnection conn = fac.createConnection(storageConf,db);
return conn.read(db,table,keycol,key);
}
public String writeEvents(String db, String table, JsonArray events) {
for (Object event: events) {
JsonObject obj = (JsonObject) event;
writeEvent(db, table, obj);
}
return "{\"msg\":\"ok\"}";
}
public String writeEvent(String db, String table, JsonObject rowObj) {
JsonObject tbl = meta.runQuery(EntityType.SERIES, db+"."+table);
if (tbl == null) throw new RuntimeException("Table "+table+" does not exist");
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) throw new RuntimeException("Storage for "+table+" does not exist");
PaasConnection conn = fac.createConnection(storageConf,db);
String periodicity = tbl.getString("periodicity");
Long time = rowObj.getLong("timestamp");
if (time == null || time <= 0) {
time = System.currentTimeMillis();
}
String prefix = rowObj.getString("prefix");
if (prefix != null && !prefix.equals("")) prefix = prefix+":"; else prefix = "";
Long rowkey = (time/Long.parseLong(periodicity))*Long.parseLong(periodicity);
rowObj.putString("columns", "key,column1,value");
rowObj.putString("values","'"+prefix+String.valueOf(rowkey)+"',"+time+",'"+rowObj.getString("event")+"'");
return conn.insert(db,table,rowObj);
}
public String readEvent(String db, String table, String eventTime) {
JsonObject tbl = meta.runQuery(EntityType.SERIES, db+"."+table);
if (tbl == null) throw new RuntimeException("Table "+table+" does not exist");
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) throw new RuntimeException("Storage for "+table+" does not exist");
PaasConnection conn = fac.createConnection(storageConf,db);
String periodicity = tbl.getString("periodicity");
Long time = Long.parseLong(eventTime);
Long rowkey = (time/Long.parseLong(periodicity))*Long.parseLong(periodicity);
return conn.read(db,table,"key",String.valueOf(rowkey),"column1",String.valueOf(eventTime));
}
public String readEvent(String db, String table, String prefix,String eventTime) {
JsonObject tbl = meta.runQuery(EntityType.SERIES, db+"."+table);
if (tbl == null) throw new RuntimeException("Table "+table+" does not exist");
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) throw new RuntimeException("Storage for "+table+" does not exist");
PaasConnection conn = fac.createConnection(storageConf,db);
String periodicity = tbl.getString("periodicity");
Long time = Long.parseLong(eventTime);
Long rowkey = (time/Long.parseLong(periodicity))*Long.parseLong(periodicity);
if (prefix != null && !prefix.equals("")) prefix = prefix+":"; else prefix = "";
return conn.read(db,table,"key",prefix+String.valueOf(rowkey),"column1",String.valueOf(eventTime));
}
public String readEvent(String db, String table, String prefix,String startTime, String endTime) {
JsonObject tbl = meta.runQuery(EntityType.SERIES, db+"."+table);
if (tbl == null) throw new RuntimeException("Table "+table+" does not exist");
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) throw new RuntimeException("Storage for "+table+" does not exist");
PaasConnection conn = fac.createConnection(storageConf,db);
String periodicity = tbl.getString("periodicity");
Long time = Long.parseLong(startTime);
Long startTimekey = (time/Long.parseLong(periodicity))*Long.parseLong(periodicity);
Long endTimeL = Long.parseLong(endTime);
Long endTimeKey = (endTimeL/Long.parseLong(periodicity))*Long.parseLong(periodicity);
if (prefix != null && !prefix.equals("")) prefix = prefix+":"; else prefix = "";
JsonObject response = new JsonObject();
for (Long current = startTimekey; current < endTimeKey;current = current+Long.parseLong(periodicity) ) {
JsonObject slice = new JsonObject(conn.read(db,table,"key",prefix+String.valueOf(current)));
for (String field:slice.getFieldNames()) {
response.putString(field, slice.getString(field));
}
}
return response.toString();
}
public String doJoin(String db, String table1, String table2,
String joincol, String value) {
String res1 = listRow(db,table1,joincol,value);
String res2 = listRow(db,table2,joincol,value);
return "{\""+table1+"\":"+res1+",\""+table2+"\":"+res2+"}";
}
public byte[] fetchValueForKey(String db, String table, String keycol,
String key) {
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) return "{\"msg\":\"the requested table does not exist in paas\"}".getBytes();
PaasConnection conn = fac.createConnection(storageConf,db);
String ret = conn.read(db,table,keycol,key);
JsonObject keyval = new JsonObject(ret).getObject("1");
String val = keyval.getString("value");
return val.getBytes();
}
public byte[] readChunked(String db, String table, String objectName) {
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) return "{\"msg\":\"the requested table does not exist in paas\"}".getBytes();
PaasConnection conn = fac.createConnection(storageConf,db);
ByteArrayOutputStream os = conn.readChunked(db, table, objectName);
return os.toByteArray();
}
public String writeChunked(String db, String table, String objectName,
InputStream is) {
// TODO Auto-generated method stub
JsonObject storageConf = meta.getStorageForTable(db+"."+table);
if (storageConf == null) return "{\"msg\":\"the requested table does not exist in paas\"}";
PaasConnection conn = fac.createConnection(storageConf,db);
return conn.writeChunked(db, table, objectName, is);
}
}
| 688 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/service/CLIENTTYPE.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.staash.service;
public enum CLIENTTYPE {
ASTYANAX("astyanax"),CQL("cql");
private String type;
CLIENTTYPE(String type) {
this.type = type;;
}
public String getType() {
return type;
}
}
| 689 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/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.staash.exception;
public class InvalidConfException extends PaasException {
private static final long serialVersionUID = 1L;
public InvalidConfException() {
super();
}
public InvalidConfException(String message) {
super(message);
}
}
| 690 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/ColumnDoesNotExistsException.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.staash.exception;
public class ColumnDoesNotExistsException extends PaasException{
public ColumnDoesNotExistsException() {
super();
// TODO Auto-generated constructor stub
}
public ColumnDoesNotExistsException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 691 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/TypeDoesNotMatchWithValueException.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.staash.exception;
public class TypeDoesNotMatchWithValueException extends PaasRuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 692 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/DBDoesNotExistException.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.staash.exception;
public class DBDoesNotExistException extends PaasException{
public DBDoesNotExistException() {
super();
// TODO Auto-generated constructor stub
}
public DBDoesNotExistException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 693 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/StorageDoesNotExistException.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.staash.exception;
public class StorageDoesNotExistException extends PaasException{
public StorageDoesNotExistException() {
super();
// TODO Auto-generated constructor stub
}
public StorageDoesNotExistException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 694 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/TableDoesNotExistException.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.staash.exception;
public class TableDoesNotExistException extends PaasException{
public TableDoesNotExistException() {
super();
// TODO Auto-generated constructor stub
}
public TableDoesNotExistException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 695 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/EntityAlreadyExistsException.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.staash.exception;
public class EntityAlreadyExistsException extends PaasException{
private static final long serialVersionUID = 1L;
public EntityAlreadyExistsException() {
super();
}
public EntityAlreadyExistsException(String message) {
// TODO Auto-generated constructor stub
super(message);
}
}
| 696 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/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.staash.exception;
public class PaasException extends Exception {
private static final long serialVersionUID = 1L;
public PaasException() {
super();
}
public PaasException(String message) {
// TODO Auto-generated constructor stub
super(message);
}
}
| 697 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/exception/PaasRuntimeException.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.staash.exception;
public class PaasRuntimeException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 698 |
0 |
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/rest
|
Create_ds/staash/staash-svc/src/main/java/com/netflix/staash/rest/tomcat/GuiceServletConfig.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.staash.rest.tomcat;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.staash.cassandra.discovery.EurekaModule;
import com.netflix.staash.rest.modules.PaasPropertiesModule;
import com.netflix.staash.rest.resources.StaashAdminResourceImpl;
import com.netflix.staash.rest.resources.StaashDataResourceImpl;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
public class GuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return LifecycleInjector.builder()
.withModules(
new EurekaModule(),
new PaasPropertiesModule(),
new JerseyServletModule() {
@Override
protected void configureServlets() {
bind(GuiceContainer.class).asEagerSingleton();
bind(StaashAdminResourceImpl.class);
bind(StaashDataResourceImpl.class);
serve("/*").with(GuiceContainer.class);
}
}
)
.createInjector();
}
}
| 699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.