Diff stringlengths 10 2k | Message stringlengths 28 159 |
|---|---|
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeMissingPolicy; | Remove this call to "exit" or ensure it is really required. |
import org.apache.accumulo.core.security.tokens.UserPassToken;
Connector conn = inst.getConnector(new UserPassToken("root", "")); | Immediately return this expression instead of assigning it to the temporary variable "ret". |
if (obj == null)
return "-";
if (tableId == null)
return "-"; | Remove this call to "exit" or ensure it is really required. |
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.security.CredentialHelper;
String sourceUserProp = props.getProperty("source", "system");
String sourceUser;
AuthenticationToken sourceToken;
if ("system".equals(sourceUserProp)) {
sourceUser = WalkingSecurity.get(state).getSysUserName();
sourceToken = WalkingSecurity.get(state).getSysToken();
} else if ("table".equals(sourceUserProp)) {
sourceUser = WalkingSecurity.get(state).getTabUserName();
sourceToken = WalkingSecurity.get(state).getTabToken();
sourceUser = state.getUserName();
sourceToken = state.getToken();
Connector conn = state.getInstance().getConnector(sourceUser, sourceToken);
canGive = WalkingSecurity.get(state).canGrantTable(CredentialHelper.create(sourceUser, sourceToken, state.getInstance().getInstanceID()), target, WalkingSecurity.get(state).getTableName()); | Immediately return this expression instead of assigning it to the temporary variable "connector". |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.util;
import org.apache.accumulo.core.data.ArrayByteSequence;
import org.apache.accumulo.core.data.ByteSequence;
public class MutableByteSequence extends ArrayByteSequence {
private static final long serialVersionUID = 1L;
public MutableByteSequence(byte[] data, int offset, int length) {
super(data, offset, length);
}
public MutableByteSequence(ByteSequence bs) {
super(new byte[Math.max(64, bs.length())]);
System.arraycopy(bs.getBackingArray(), bs.offset(), data, 0, bs.length());
this.length = bs.length();
this.offset = 0;
}
public void setArray(byte[] data, int offset, int len) {
this.data = data;
this.offset = offset;
this.length = len;
}
public void setLength(int len) {
this.length = len;
}
} | Either log or rethrow this exception. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.accumulo.proxy.thrift;
import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;
@SuppressWarnings("all") public enum ScanType implements org.apache.thrift.TEnum {
SINGLE(0),
BATCH(1);
private final int value;
private ScanType(int value) {
this.value = value;
}
/**
* Get the integer value of this enum value, as defined in the Thrift IDL.
*/
public int getValue() {
return value;
}
/**
* Find a the enum type by its integer value, as defined in the Thrift IDL.
* @return null if the value is not found.
*/
public static ScanType findByValue(int value) {
switch (value) {
case 0:
return SINGLE;
case 1:
return BATCH;
default:
return null;
}
}
} | Return empty string instead. |
@Deprecated | Remove this unused method parameter "ex". |
import org.apache.accumulo.fate.zookeeper.IZooReaderWriter; | Remove this call to "exit" or ensure it is really required. |
checkRFiles(TABLE_NAME, 1, 1, 100, 100);
checkRFiles(TABLE_NAME, 50, 100, 1, 4); | Either log or rethrow this exception. |
SimpleTimer.getInstance().schedule(new Runnable() { | Either log or rethrow this exception. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | 2 duplicated blocks of code must be removed. |
* Provides programs to analyze metadata mutations written to write ahead logs.
*
* which write ahead logs contain metadata mutations is to grep the tablet server logs.
* Grep for events where walogs were added to metadata tablets, then take the unique set
* To use these programs, use IndexMeta to index the metadata mutations in walogs into
* Accumulo tables. Then use FindTable and PrintEvents to analyze those indexes. | Replace all tab characters in this file by sequences of white-spaces. |
private static final short NON_NUMERIC_VALUE = 1;
private boolean isNumeric(byte bytes[]) {
for (byte b : bytes) {
boolean ok = (b >= '0' && b <= '9');
if (!ok) return false;
return true;
}
private List<Short> addViolation(List<Short> violations, short violation) {
if (violations == null) {
violations = new ArrayList<Short>();
violations.add(violation);
} else if (!violations.contains(violation)) {
violations.add(violation);
return violations;
}
@Override
public List<Short> check(Environment env, Mutation mutation) {
List<Short> violations = null;
Collection<ColumnUpdate> updates = mutation.getUpdates();
for (ColumnUpdate columnUpdate : updates) {
if (!isNumeric(columnUpdate.getValue())) violations = addViolation(violations, NON_NUMERIC_VALUE);
return violations;
}
@Override
public String getViolationDescription(short violationCode) {
switch (violationCode) {
case NON_NUMERIC_VALUE:
return "Value is not numeric";
return null;
}
| Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
import org.apache.accumulo.server.cli.ClientOpts;
import com.beust.jcommander.Parameter;
static class Opts extends ClientOpts {
@Parameter(names="--readonly", description="read only")
boolean readonly = false;
@Parameter(names="--tables", description="number of tables to create")
int tables = 5;
@Parameter(names="--count", description="number of entries to create")
int count = 10000;
private static void readBack(Opts opts, Connector conn) throws Exception {
Scanner scanner = conn.createScanner(table, opts.auths);
scanner.setBatchSize(opts.scanBatchSize);
if (!elt.getKey().getRow().toString().equals(expected))
throw new RuntimeException("entry " + elt + " does not match expected " + expected + " in table " + table);
Opts opts = new Opts();
opts.parseArgs(TestMultiTableIngest.class.getName(), args);
connector = opts.getConnector();
for (int i = 0; i < opts.tables; i++) {
if (!opts.readonly) {
b = connector.createMultiTableBatchWriter(opts.getBatchWriterConfig());
for (int i = 0; i < opts.count; i++) {
readBack(opts, connector); | Remove this call to "exit" or ensure it is really required. |
if (span.parentId <= 0)
count++; | Remove this call to "exit" or ensure it is really required. |
package org.apache.accumulo.core.util.shell.commands;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* EscapeTokenizer
* - Supports tokenizing with delimiters while being able to escape the delims.
* String "1,2,3,4" with delims "," = ["1", "2", "3", "4"]
* String "1\,2,3,4" with delims "," = ["1,2", "3", "4"]
*
* - The escape char '\' only has a special meaning when it is before a delim
* String "1,\2,3,4" with delims "," = ["1" , "\2", "3", "4"]
*
* - Multiple delims in a row are considered one delim
* String "1,,,,,,,,,,,,,,2,3,4","," with delims "," = ["1", "2", "3", "4"]
*
*/
public class EscapeTokenizer implements Iterable<String> {
private List<String> tokens;
public EscapeTokenizer(String line, String delimeters) {
this.tokens = new ArrayList<String>();
preprocess(line, delimeters);
}
private void preprocess(String line, String delimeters) {
StringTokenizer st = new StringTokenizer(line, delimeters, true);
boolean inEscape = false;
String current = "", prev = "";
List<String> toks = new ArrayList<String>();
while (st.hasMoreTokens()) {
current = st.nextToken();
if (inEscape) {
prev += current;
inEscape = false;
}
else {
inEscape = current.endsWith("\\");
if (inEscape)
prev = current.substring(0, current.length() - 1);
else {
if (current.length() == 1 && delimeters.contains(current))
{
if (! prev.isEmpty())
toks.add(prev);
}
else
toks.add(prev + current);
prev = "";
}
}
}
if (! prev.isEmpty())
toks.add(prev);
this.tokens = toks;
}
@Override
public Iterator<String> iterator() {
return this.tokens.iterator();
}
public int count() {
return tokens.size();
}
} | Return empty string instead. |
Iterator<Key> iter = uids.iterator(); | Define and throw a dedicated exception instead of using a generic one. |
return Base64.decodeBase64(conf.get(PASSWORD, "").getBytes());
return authString == null ? Constants.NO_AUTHS : new Authorizations(authString.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(rangeString.getBytes()));
Text cf = new Text(idx < 0 ? Base64.decodeBase64(col.getBytes()) : Base64.decodeBase64(col.substring(0, idx).getBytes()));
Text cq = idx < 0 ? null : new Text(Base64.decodeBase64(col.substring(idx + 1).getBytes()));
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(itstring.getBytes())); | Remove this unused method parameter "ex". |
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
private static Map<String,TableConfiguration> tableInstances = new HashMap<String,TableConfiguration>(1);
public static synchronized SiteConfiguration getSiteConfiguration() {
private static synchronized ZooConfiguration getZooConfiguration() {
public static synchronized DefaultConfiguration getDefaultConfiguration() {
public static synchronized AccumuloConfiguration getSystemConfiguration() {
public static TableConfiguration getTableConfiguration(String instanceId, String tableId) {
static void removeTableIdInstance(String tableId) {
static void expireAllTableObservers() {
for (Entry<String,TableConfiguration> entry : tableInstances.entrySet()) { | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.accumulo.proxy.thrift;
import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;
@SuppressWarnings("all") public enum CompactionType implements org.apache.thrift.TEnum {
MINOR(0),
MERGE(1),
MAJOR(2),
FULL(3);
private final int value;
private CompactionType(int value) {
this.value = value;
}
/**
* Get the integer value of this enum value, as defined in the Thrift IDL.
*/
public int getValue() {
return value;
}
/**
* Find a the enum type by its integer value, as defined in the Thrift IDL.
* @return null if the value is not found.
*/
public static CompactionType findByValue(int value) {
switch (value) {
case 0:
return MINOR;
case 1:
return MERGE;
case 2:
return MAJOR;
case 3:
return FULL;
default:
return null;
}
}
} | Return empty string instead. |
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
try {
String monitorAddress = org.apache.accumulo.core.util.AddressUtil.toString(new InetSocketAddress(hostname, server.getPort()));
ZooReaderWriter.getInstance().putPersistentData(ZooUtil.getRoot(instance) + Constants.ZMONITOR, monitorAddress.getBytes(),
NodeExistsPolicy.OVERWRITE);
log.info("Set monitor address in zookeeper to " + monitorAddress);
} catch (Exception ex) {
log.error("Unable to set monitor address in zookeeper");
}
LogService.startLogListener(Monitor.getSystemConfiguration(), instance.getInstanceID());
| Either log or rethrow this exception. |
// Ensure that the visibility (which could have been transformed) parses. Must always do this check, even if visibility is not evaluated.
ColumnVisibility colVis = null;
Boolean parsed = (Boolean) parsedVisibilitiesCache.get(visibility);
if (parsed == null) {
parsedVisibilitiesCache.put(visibility, Boolean.TRUE);
log.error("Parse error after transformation : " + visibility);
parsedVisibilitiesCache.put(visibility, Boolean.FALSE);
if (scanning) {
return false;
} else {
throw e;
}
} else if (!parsed) {
if (scanning)
return false;
else
throw new IllegalStateException();
if (!scanning || !visible || ve == null || visibleCache == null || visibility.length() == 0)
if (colVis == null)
colVis = new ColumnVisibility(visibility.toArray()); | Either log or rethrow this exception. |
CRYPTO_CIPHER_ALGORITHM_NAME("crypto.cipher.algorithm.name", "NullCipher", PropertyType.STRING,
MASTER_WALOG_CLOSER_IMPLEMETATION("master.walog.closer.implementation", "org.apache.accumulo.server.master.recovery.HadoopLogCloser",
PropertyType.CLASSNAME, "A class that implements a mechansim to steal write access to a file"),
VFS_CLASSLOADER_CACHE_DIR(
AccumuloVFSClassLoader.VFS_CACHE_DIR,
new File(System.getProperty("java.io.tmpdir"), "accumulo-vfs-cache")
.getAbsolutePath(),
PropertyType.ABSOLUTEPATH,
"Directory to use for the vfs cache. The cache will keep a soft reference to all of the classes loaded in the VM. This should be on local disk on each node with sufficient space. It defaults to /tmp",
false);
if (key.startsWith(prefix))
for (Property prop : Property.values())
if (prop.getKey().equals(key))
| Replace all tab characters in this file by sequences of white-spaces. |
private final Map<String,LogProcessor> currentWork = Collections.synchronizedMap(new HashMap<String,LogProcessor>()); | Move this variable to comply with Java Code Conventions. |
import java.nio.charset.Charset;
private static final Charset utf8 = Charset.forName("UTF8");
mfw.append(rootDirKey, new Value("/root_tablet".getBytes(utf8)));
mfw.append(tableDirKey, new Value(Constants.TABLE_TABLET_LOCATION.getBytes(utf8)));
mfw.append(tableTimeKey, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(utf8)));
mfw.append(defaultDirKey, new Value(Constants.DEFAULT_TABLET_LOCATION.getBytes(utf8)));
mfw.append(defaultTimeKey, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes(utf8)));
zoo.putPersistentData(instanceNamePath, uuid.getBytes(utf8), NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTER_GOAL_STATE, MasterGoalState.NORMAL.toString().getBytes(utf8), NodeExistsPolicy.FAIL);
return cliPassword.getBytes(utf8);
return rootpass.getBytes(utf8); | Move this variable to comply with Java Code Conventions. |
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws IOException {
final long trace = Trace.currentTrace().traceId();
final Map<String,String> properties = shellState.getConnector().instanceOperations().getSystemConfiguration();
final String table = properties.get(Property.TRACE_TABLE.getKey());
final String user = shellState.getConnector().whoami();
final Authorizations auths = shellState.getConnector().securityOperations().getUserAuthorizations(user);
final Scanner scanner = shellState.getConnector().createScanner(table, auths);
public void print(final String line) { | Remove the redundant '!unknownSymbol!' thrown exception declaration(s). |
package org.apache.accumulo.examples.wikisearch.ingest; | Rename "table" which hides the field declared at line 107. |
package org.apache.accumulo.examples.wikisearch.normalizer; | 2 duplicated blocks of code must be removed. |
import org.junit.Test;
public class CreateAndUseIT extends MacTest {
@Test(timeout=60*1000) | Either log or rethrow this exception. |
import org.apache.accumulo.core.security.thrift.SecurityErrorCode; | 1 duplicated blocks of code must be removed. |
package org.apache.accumulo.core.util;
import org.apache.hadoop.conf.Configuration;
public class CachedConfiguration {
private static Configuration configuration = null;
public synchronized static Configuration getInstance() {
if (configuration == null)
setInstance(new Configuration());
return configuration;
}
public synchronized static Configuration setInstance(Configuration update) {
Configuration result = configuration;
configuration = update;
return result;
}
} | Return empty string instead. |
private final String tabletDirectory;
this.tabletDirectory = location.toString();
newTablets.put(high, new SplitInfo(tabletDirectory, highDatafileSizes, time, lastFlushID, lastCompactID)); | Return empty string instead. |
* Autogenerated by Thrift Compiler (0.9.0) | Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'. |
@Deprecated | Return empty string instead. |
public int getOnlineCount();
public int getOpeningCount();
public int getUnopenedCount();
public int getMajorCompactions();
public int getMajorCompactionsQueued();
public int getMinorCompactions();
public int getMinorCompactionsQueued();
public long getEntries();
public long getEntriesInMemory();
public long getQueries();
public long getIngest();
public long getTotalMinorCompactions();
public double getHoldTime();
public String getName();
public double getAverageFilesPerTablet(); | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
System.out.println("Classname " + (args.length > 2 ? args[2] : "in JAR manifest")
+ " not found. Please make sure you use the wholly qualified package name.");
@Override
System.out
.println("accumulo init | master | tserver | monitor | shell | admin | gc | classpath | rfile-info | login-info | tracer | minicluster | proxy | zookeeper | create-token | info | version | jar <jar> [<main class>] args | <accumulo class> args");
return cl.loadClass(args[2]); // jar jar-file main-class | Define and throw a dedicated exception instead of using a generic one. |
import org.apache.accumulo.core.security.thrift.Credentials;
private static Credentials credentials;
Connector connector = HdfsZooInstance.getInstance().getConnector(credentials.getPrincipal(), credentials.getToken()); | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
import org.apache.accumulo.core.security.thrift.Credential;
import org.apache.accumulo.core.security.thrift.tokens.SecurityToken;
public interface Authenticator extends org.apache.accumulo.core.security.handler.Authenticator {
public void initializeSecurity(Credential credentials, String principal, byte[] token) throws AccumuloSecurityException, ThriftSecurityException;
public boolean authenticateUser(String principal, SecurityToken token) throws AccumuloSecurityException;
public void createUser(String principal, SecurityToken token) throws AccumuloSecurityException;
public void changePassword(String principal, SecurityToken token) throws AccumuloSecurityException;
public String getTokenLoginClass();
/**
* Returns true if the given token is appropriate for this Authenticator
*/
public boolean validTokenClass(String tokenClass); | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
* @param t
* @param s | Either log or rethrow this exception. |
package org.apache.accumulo.examples.wikisearch.logic;
import org.apache.accumulo.examples.wikisearch.iterator.EvaluatingIterator;
import org.apache.accumulo.examples.wikisearch.parser.RangeCalculator;
import org.apache.accumulo.examples.wikisearch.parser.QueryParser.QueryTerm; | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
public static MapFile.Reader openMapFile(AccumuloConfiguration acuconf, FileSystem fs, String dirName, Configuration conf) throws IOException {
MapFile.Reader mfr = null;
mfr = new MapFile.Reader(fs, dirName, conf);
public static SequenceFile.Reader openIndex(Configuration conf, FileSystem fs, Path mapFile) throws IOException {
Path indexPath = new Path(mapFile, MapFile.INDEX_FILE_NAME);
SequenceFile.Reader index = null;
index = new SequenceFile.Reader(fs, indexPath, conf); | Remove this unused method parameter "acuconf". |
import org.apache.accumulo.core.security.Authorizations;
Authorizations.EMPTY); | Remove this unused method parameter "range". |
List<ByteBuffer> tableSplits = tpc.proxy().listSplits(userpass, testtable, 10);
List<ByteBuffer> tableSplits = tpc.proxy().listSplits(userpass, testtable, 10); | Remove the redundant '!unknownSymbol!' thrown exception declaration(s). |
/**
* Takes a list of files and archives them into Accumulo keyed on the SHA1 hashes of the files. See docs/examples/README.filedata for instructions.
*/ | 1 duplicated blocks of code must be removed. |
WalkingSecurity.get(state).createUser(systemUserName, sysUserPass);
WalkingSecurity.get(state).changePassword(tableUserName, new byte[0]);
WalkingSecurity.get(state).setTableName(secTableName);
WalkingSecurity.get(state).setTabUserName(tableUserName);
WalkingSecurity.get(state).revokeTablePermission(systemUserName, secTableName, tp);
WalkingSecurity.get(state).revokeTablePermission(tableUserName, secTableName, tp);
WalkingSecurity.get(state).revokeSystemPermission(systemUserName, sp);
WalkingSecurity.get(state).revokeSystemPermission(tableUserName, sp);
WalkingSecurity.get(state).changeAuthorizations(tableUserName, new Authorizations());
if (WalkingSecurity.get(state).getTableExists()) {
String secTableName = WalkingSecurity.get(state).getTableName();
if (WalkingSecurity.get(state).userExists(WalkingSecurity.get(state).getTabUserName())) {
String tableUserName = WalkingSecurity.get(state).getTabUserName();
String systemUserName = WalkingSecurity.get(state).getSysUserName(); | Reduce this switch case number of lines from 44 to at most 5, for example by extracting code into methods. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@SuppressWarnings("all") public enum _Fields implements org.apache.thrift.TFieldIdEnum { | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
import org.apache.accumulo.core.cli.ScannerOpts;
ScannerOpts scanOpts = new ScannerOpts();
opts.parseArgs(ReadData.class.getName(), args, scanOpts);
scan.setBatchSize(scanOpts.scanBatchSize); | Remove this unused method parameter "opts". |
import org.apache.accumulo.core.security.Credentials;
public <T extends Mutation> void binMutations(Credentials credentials, List<T> mutations, Map<String,TabletServerMutations<T>> binnedMutations, List<T> failures)
throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
public List<Range> binRanges(Credentials credentials, List<Range> ranges, Map<String,Map<KeyExtent,List<Range>>> binnedRanges) throws AccumuloException,
public TabletLocation locateTablet(Credentials credentials, Text row, boolean skipRow, boolean retry) throws AccumuloException, AccumuloSecurityException, | Immediately return this expression instead of assigning it to the temporary variable "onlineTabletsForTable". |
/**
* Constructor
*
* @param s
* message.
*/
MetaBlockAlreadyExists(String s) {
super(s);
} | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
* {@link BatchDeleter} for a {@link MockAccumulo} instance. Behaves similarly to a regular {@link BatchDeleter}, with a few exceptions:
* Create a {@link BatchDeleter} for the specified instance on the specified table where the writer uses the specified {@link Authorizations}.
*
public MockBatchDeleter(MockAccumulo acc, String tableName, Authorizations auths) {
public void delete() throws MutationsRejectedException, TableNotFoundException {
Iterator<Entry<Key,Value>> iter = super.iterator();
Entry<Key,Value> next = iter.next();
m.putDelete(k.getColumnFamily(), k.getColumnQualifier(), new ColumnVisibility(k.getColumnVisibility()), k.getTimestamp());
| Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
import java.net.Socket;
while (true) {
try {
Socket s = new Socket("localhost", config.getZooKeeperPort());
s.getOutputStream().write("ruok\n".getBytes());
s.getOutputStream().flush();
byte buffer[] = new byte[100];
int n = s.getInputStream().read(buffer);
if (n == 4 && new String(buffer, 0, n).equals("imok"))
break;
} catch (Exception e) {
UtilWaitThread.sleep(250);
}
} | Either log or rethrow this exception. |
import java.util.Map.Entry; | Replace all tab characters in this file by sequences of white-spaces. |
if (newFinish != -1)
lastFinish = newFinish;
if (lastStartToFinish.compactionStatus == Status.LOOKING_FOR_FINISH)
throw new RuntimeException("COMPACTION_FINISH (without preceding COMPACTION_START) not followed by successful minor compaction");
if (!reader.next(key, value))
throw new RuntimeException("Unable to read log entries");
if (key.event != OPEN)
throw new RuntimeException("First log entry value is not OPEN");
if (lastStartToFinish.compactionStatus == Status.LOOKING_FOR_FINISH)
throw new RuntimeException("COMPACTION_FINISH (without preceding COMPACTION_START) is not followed by a successful minor compaction.");
if (key.event != DEFINE_TABLET)
break;
if (key.tid != tid)
break;
if (lastStartToFinish.compactionStatus == Status.INITIAL)
lastStartToFinish.compactionStatus = Status.COMPLETE;
if (key.seq <= lastStartToFinish.lastStart)
throw new RuntimeException("Sequence numbers are not increasing for start/stop events.");
if (tabletFiles.contains(key.filename))
lastStartToFinish.update(-1);
if (key.seq <= lastStartToFinish.lastStart)
throw new RuntimeException("Sequence numbers are not increasing for start/stop events.");
if (lastStartToFinish.compactionStatus == Status.INITIAL)
lastStartToFinish.compactionStatus = Status.LOOKING_FOR_FINISH;
else if (lastStartToFinish.lastFinish > lastStartToFinish.lastStart)
throw new RuntimeException("COMPACTION_FINISH does not have preceding COMPACTION_START event.");
else
lastStartToFinish.compactionStatus = Status.COMPLETE;
} else
break;
if (!reader.next(key, value))
break;
if (key.tid != tid)
break; | Remove this call to "exit" or ensure it is really required. |
@Parameter(names = "--readonly", description = "read only")
@Parameter(names = "--tables", description = "number of tables to create")
@Parameter(names = "--count", description = "number of entries to create") | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
package org.apache.accumulo.examples.simple.filedata;
import org.apache.accumulo.examples.simple.filedata.ChunkCombiner;
import org.apache.accumulo.examples.simple.filedata.FileDataIngest; | 2 duplicated blocks of code must be removed. |
if (obj == null)
return "-";
if (errMin != null && errMax != null)
return seconds(millis, errMin, errMax);
if (secs < errMin || secs > errMax)
return "<span class='error'>" + numbers + "</span>"; | Remove this call to "exit" or ensure it is really required. |
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Override
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws IOException {
for (String p : SystemPermission.printableValues())
shellState.getReader().printString(p + "\n");
return 0;
}
@Override
public String description() {
return "displays a list of valid system permissions";
}
@Override
public int numArgs() {
return 0;
} | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
public static class LogWriter extends Thread {
public List<LogWriter> getLogWriters() {
return logWriters;
}
| Remove this unused method parameter "range". |
import org.apache.accumulo.core.security.tokens.UserPassToken;
assertArrayEquals("secret".getBytes(), ((UserPassToken) args.getAccumuloToken()).getPassword());
assertArrayEquals("foo".getBytes(), ((UserPassToken) args.getAccumuloToken()).getPassword()); | Return empty string instead. |
package org.apache.accumulo.core.file.blockfile;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
/*
* Minimal interface to read a block from a
* block based file
*
*/
public interface ABlockReader extends DataInput{
public long getRawSize();
public DataInputStream getStream() throws IOException;
public void close() throws IOException;
} | Return empty string instead. |
/**
* A filter that ages off key/value pairs based on the Key's timestamp. It removes an entry if its timestamp is less than currentTime - threshold.
*
* This filter requires a "ttl" option, in milliseconds, to determine the age off threshold.
*/
/**
* Constructs a filter that omits entries read from a source iterator if the Key's timestamp is less than currentTime - threshold.
*
* @param iterator
* The source iterator.
*
* @param threshold
* Maximum age in milliseconds of data to keep.
*
* @param threshold
* Current time in milliseconds.
*/
/**
* Accepts entries whose timestamps are less than currentTime - threshold.
*
* @see org.apache.accumulo.core.iterators.Filter#accept(org.apache.accumulo.core.data.Key, org.apache.accumulo.core.data.Value)
*/ | Remove the literal "true" boolean value. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
* @see #setConnectorInfo(Class, Configuration, String, byte[]) | Remove the redundant '!unknownSymbol!' thrown exception declaration(s). |
import org.apache.accumulo.core.client.security.tokens.PasswordToken; | 1 duplicated blocks of code must be removed. |
private Option disablePaginationOpt;
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws ShellCommandException, IOException {
// print help summary
if (cl.getArgs().length == 0) {
int i = 0;
for (String cmd : shellState.commandFactory.keySet())
i = Math.max(i, cmd.length());
ArrayList<String> output = new ArrayList<String>();
for (Command c : shellState.commandFactory.values()) {
if (!(c instanceof HiddenCommand)) output.add(String.format("%-" + i + "s - %s", c.getName(), c.description()));
}
shellState.printLines(output.iterator(), !cl.hasOption(disablePaginationOpt.getOpt()));
// print help for every command on command line
for (String cmd : cl.getArgs()) {
try {
shellState.commandFactory.get(cmd).printHelp();
} catch (Exception e) {
Shell.printException(e);
return 1;
}
return 0;
}
public String description() {
return "provides information about the available commands";
}
public void registerCompletion(Token root, Map<Command.CompletionSet,Set<String>> special) {
registerCompletionForCommands(root, special);
}
@Override
public Options getOptions() {
Options o = new Options();
disablePaginationOpt = new Option("np", "no-pagination", false, "disables pagination of output");
o.addOption(disablePaginationOpt);
return o;
}
@Override
public String usage() {
return getName() + " [ <command>{ <command>} ]";
}
@Override
public int numArgs() {
return Shell.NO_FIXED_ARG_LENGTH_CHECK;
} | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
return Long.toString(v).getBytes(); | Remove this unused private "appendProp" method. |
import org.apache.accumulo.core.security.tokens.PasswordToken;
import org.apache.accumulo.core.security.tokens.SecurityToken;
SecurityToken token = this.getToken();
String passwd = "";
if (token instanceof PasswordToken) {
passwd = new String(((PasswordToken)token).getPassword());
}
VerifyIngest.main(new String[] {"--timestamp", "1", "--size", "50", "--random", "56", "--rows", "100000", "--start", "0", "--cols", "1", "-p", passwd}); | Remove this hard-coded password. |
import java.util.Map.Entry;
Shell.log.warn("Deprecated, use " + new SetShellIterCommand().getName());
protected void setTableProperties(final CommandLine cl, final Shell shellState, final int priority, final Map<String,String> options, final String classname,
final String name) throws AccumuloException, AccumuloSecurityException, ShellCommandException, TableNotFoundException {
final String tableName = OptUtil.getTableOpt(cl, shellState);
for (Iterator<Entry<String,String>> i = options.entrySet().iterator(); i.hasNext();) {
final Entry<String,String> entry = i.next();
if (entry.getValue() == null || entry.getValue().isEmpty()) {
i.remove();
}
}
| Move this constructor to comply with Java Code Conventions. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
import java.util.Set; | Replace all tab characters in this file by sequences of white-spaces. |
import org.apache.accumulo.cloudtrace.instrument.Tracer;
import org.apache.accumulo.cloudtrace.thrift.TInfo;
TInfo tinfo = Tracer.traceInfo();
TabletClientService.Client client = ThriftUtil.getTServerClient(server, conf);
InitialScan isr = client.startScan(tinfo, scanState.credentials, extent.toThrift(), scanState.range.toThrift(),
client.closeScan(tinfo, isr.scanID);
TInfo tinfo = Tracer.traceInfo();
TabletClientService.Client client = ThriftUtil.getTServerClient(loc.tablet_location, conf);
InitialScan is = client.startScan(tinfo, scanState.credentials, loc.tablet_extent.toThrift(), scanState.range.toThrift(),
client.closeScan(tinfo, is.scanID);
sr = client.continueScan(tinfo, scanState.scanID);
client.closeScan(tinfo, scanState.scanID); | Immediately return this expression instead of assigning it to the temporary variable "client". |
/**
* @deprecated since 1.5, use {@link #fetch(ScannerBase)} instead
*/
public static void fetch(ScannerBase sb, ColumnFQ cfq) {
sb.fetchColumn(cfq.colf, cfq.colq);
}
/**
* @deprecated since 1.5, use {@link #put(Mutation, Value)} instead
*/
public static void put(Mutation m, ColumnFQ cfq, Value v) {
m.put(cfq.colf, cfq.colq, v);
}
/**
* @deprecated since 1.5, use {@link #putDelete(Mutation)} instead
*/
public static void putDelete(Mutation m, ColumnFQ cfq) {
m.putDelete(cfq.colf, cfq.colq);
} | Do not forget to remove this deprecated code someday. |
public static final String AUDITLOG = "Audit";
public static final Logger audit = Logger.getLogger(AUDITLOG);
| Make the "audit" logger private static final and rename it to comply with the format "LOG(?:GER)?". |
AuthInfo auth = new AuthInfo("root", ByteBuffer.wrap("".getBytes()), "instance"); | 2 duplicated blocks of code must be removed. |
public class ZooReader implements IZooReader {
@Override
@Override
@Override
@Override
@Override
@Override
@Override | Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
import org.apache.accumulo.examples.wikisearch.parser.RangeCalculator;
return Collections.singletonList(new Range()); | 31 duplicated blocks of code must be removed. |
import org.apache.accumulo.core.security.thrift.ThriftSecurityException; | 1 duplicated blocks of code must be removed. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
public void initialize(String instanceId, boolean initialize); | Remove this call to "exit" or ensure it is really required. |
package org.apache.accumulo.server.test.randomwalk.concurrent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.TableDeletedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.server.test.randomwalk.State;
import org.apache.accumulo.server.test.randomwalk.Test;
public class BatchScan extends Test {
@Override
public void visit(State state, Properties props) throws Exception {
Connector conn = state.getConnector();
Random rand = (Random) state.get("rand");
@SuppressWarnings("unchecked")
List<String> tableNames = (List<String>) state.get("tables");
String tableName = tableNames.get(rand.nextInt(tableNames.size()));
try {
BatchScanner bs = conn.createBatchScanner(tableName, Constants.NO_AUTHS, 3);
List<Range> ranges = new ArrayList<Range>();
for(int i = 0; i < rand.nextInt(2000)+1; i++)
ranges.add(new Range(String.format("%016x", Math.abs(rand.nextLong()))));
bs.setRanges(ranges);
try{
Iterator<Entry<Key, Value>> iter = bs.iterator();
while (iter.hasNext())
iter.next();
}finally{
bs.close();
}
log.debug("Wrote to "+tableName);
} catch (TableNotFoundException e) {
log.debug("BatchScan "+tableName+" failed, doesnt exist");
} catch (TableDeletedException tde){
log.debug("BatchScan "+tableName+" failed, table deleted");
} catch (TableOfflineException e){
log.debug("BatchScan "+tableName+" failed, offline");
}
}
}
| Return empty string instead. |
package org.apache.accumulo.examples.simple.client; | Rename "table" which hides the field declared at line 107. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
import org.apache.accumulo.core.client.BatchWriterConfig;
BatchWriter bw = getConnector().createBatchWriter("rdel1", new BatchWriterConfig()); | Remove this unused method parameter "e". |
@SuppressWarnings("all") public class ThriftSecurityException extends Exception implements org.apache.thrift.TBase<ThriftSecurityException, ThriftSecurityException._Fields>, java.io.Serializable, Cloneable { | 13 duplicated blocks of code must be removed. |
Path recoveryPath = new Path(Constants.getRecoveryDir(acuConf), filename);
try {
if (trash.moveToTrash(recoveryPath) || fs.delete(recoveryPath, true))
log.info("Deleted any recovery log " + filename);
} catch (FileNotFoundException ex) {
// ignore
} | Either log or rethrow this exception. |
import org.apache.accumulo.core.security.Authorizations;
final Scanner scanner = opts.getConnector().createScanner(Constants.METADATA_TABLE_NAME, Authorizations.EMPTY); | Remove this unused method parameter "range". |
import java.util.Collections;
lfv.mutations = Collections.singletonList(m); | Remove this unused method parameter "timestamp". |
package org.apache.accumulo.test.functional; | Move the "org.apache.accumulo.test.randomwalk.unit.CreateTable" string literal on the left side of this string comparison. |
public class CreateUserCommand extends Command {
Shell.log.debug("Created user " + user); | 1 duplicated blocks of code must be removed. |
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* | Replace all tab characters in this file by sequences of white-spaces. |
log.info("Instance " + config.getInstance().getInstanceID());
| Return empty string instead. |
*
*
*
*
*
*
*
*
*
*
* | Replace all tab characters in this file by sequences of white-spaces. |
import org.apache.accumulo.core.util.AddressUtil; | 2 duplicated blocks of code must be removed. |
public static FinalCloseDefaultFileSystemManager generateVfs(boolean reloading) throws FileSystemException {
FinalCloseDefaultFileSystemManager vfs = new FinalCloseDefaultFileSystemManager(); | Do not override the Object.finalize() method. |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | Replace all tab characters in this file by sequences of white-spaces. |
* @since 1.5.0
* @since 1.5.0 | Move this constructor to comply with Java Code Conventions. |
import org.apache.accumulo.core.security.thrift.TCredentials;
TCredentials auths = CredentialHelper.create("root", new PasswordToken(new byte[0]), "instance");
| Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.