Diff
stringlengths
10
2k
Message
stringlengths
28
159
Assert.assertTrue(setting.getOptions().isEmpty()); Assert.assertFalse(setting.getOptions().isEmpty()); Assert.assertEquals(Collections.singletonMap("key", "value"), setting.getOptions());
Immediately return this expression instead of assigning it to the temporary variable "bos2".
for (int i = 0; i < counts.length; i++) double ratioFirst = timings.get(0) / timings.get(i);
Replace all tab characters in this file by sequences of white-spaces.
if (!fs.getConf().getBoolean(DFS_SUPPORT_APPEND, false)) {
Merge this if statement with the enclosing one.
package org.apache.accumulo.test.randomwalk.bulk; import org.apache.accumulo.test.randomwalk.State; import org.apache.accumulo.test.randomwalk.Test;
Move the "org.apache.accumulo.test.randomwalk.unit.CreateTable" string literal on the left side of this string comparison.
import org.apache.accumulo.core.security.thrift.TCredentials; public static synchronized TabletLocator getInstance(Instance instance, TCredentials credentials, Text tableId) {
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. */
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
conf.set(enumToConfKey(implementingClass, ConnectorInfo.TOKEN_CLASS), token.getClass().getName());
Use "Integer.toString" instead.
/* import org.apache.accumulo.core.util.ComparablePair; public class PairLexicoder<A extends Comparable<A>,B extends Comparable<B>> implements Lexicoder<ComparablePair<A,B>> { public byte[] encode(ComparablePair<A,B> data) { public ComparablePair<A,B> decode(byte[] data) { return new ComparablePair<A,B>(firstLexicoder.decode(unescape(fields[0])), secondLexicoder.decode(unescape(fields[1])));
Override "equals(Object obj)" to comply with the contract of the "compareTo(T o)" method.
public AuthenticationToken login(String principal, Properties properties) throws AccumuloSecurityException { throw new AccumuloSecurityException(principal, SecurityErrorCode.INSUFFICIENT_PROPERTIES);
Remove this unused method parameter "principal".
* Autogenerated by Thrift Compiler (0.9.0) import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; private byte __isset_bitfield = 0; __isset_bitfield = other.__isset_bitfield; __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SCANID_ISSET_ID); return EncodingUtils.testBit(__isset_bitfield, __SCANID_ISSET_ID); __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SCANID_ISSET_ID, value); // check for sub-struct validity if (result != null) { result.validate(); } __isset_bitfield = 0;
Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.
if (iter.hasNext()) top = iter.next(); else top = null; if (!inclusive && columnFamilies.size() > 0) throw new UnsupportedOperationException(); if (isolated) smi.scanner.enableIsolation(); else smi.scanner.disableIsolation();
Remove this call to "exit" or ensure it is really required.
@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 srcTableName = tableNames.get(rand.nextInt(tableNames.size())); String newTableName = tableNames.get(rand.nextInt(tableNames.size())); try { conn.tableOperations().rename(srcTableName, newTableName); log.debug("Renamed table " + srcTableName + " " + newTableName); } catch (TableExistsException e) { log.debug("Rename " + srcTableName + " failed, " + newTableName + " exist"); } catch (TableNotFoundException e) { log.debug("Rename " + srcTableName + " failed, doesnt exist"); }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
SimpleTimer.getInstance().schedule(new Runnable() {
Return empty string instead.
StringBuilder buf = new StringBuilder(); for (FileObject f : files) { try { buf.append("\t").append(f.getURL().toString()).append("\n"); } catch (FileSystemException e) { log.error("Error getting URL for file", e); } } return buf.toString();
Complete the task associated to this TODO comment.
import org.apache.accumulo.server.cli.ClientOnDefaultTable; import com.beust.jcommander.Parameter; static class Opts extends ClientOnDefaultTable { @Parameter(names={"-readonly", "--readonly"}, description="read only") boolean readOnly = false; @Parameter(names={"-count", "--count"}, description="count", required = true) int count = 10000; Opts() { super("mrtest1"); } } private static void readBack(Connector conn, Opts opts) throws Exception { Scanner scanner = conn.createScanner("mrtest1", opts.auths); scanner.setBatchSize(opts.scanBatchSize); assert (opts.count == count); String program = CreateTestTable.class.getName(); Opts opts = new Opts(); opts.parseArgs(program, args); Connector connector = opts.getConnector(); if (!opts.readOnly) { for (int i = 0; i < opts.count / 100; i++) { connector.tableOperations().create(opts.getTableName()); connector.tableOperations().addSplits(opts.getTableName(), keys); BatchWriter b = connector.createBatchWriter(opts.getTableName(), opts.getBatchWriterConfig()); for (int i = 0; i < opts.count; i++) { readBack(connector, opts); opts.stopTracing();
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. */ @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 java.util.ArrayList; import java.util.List; import java.util.TreeSet; public static final int LOTS = 100000; TreeSet<Integer> startRows = new TreeSet<Integer>(); startRows.add(0); while (startRows.size() < parts) startRows.add(rand.nextInt(LOTS)); List<String> printRows = new ArrayList<String>(startRows.size()); for (Integer row : startRows) printRows.add(String.format(FMT, row)); log.debug("preparing bulk files with start rows " + printRows + " last row " + String.format(FMT, LOTS - 1)); List<Integer> rows = new ArrayList<Integer>(startRows); rows.add(LOTS); int start = rows.get(i); int end = rows.get(i + 1); for (int j = start; j < end; j++) { String row = String.format(FMT, j); f.append(new Key(row, "cf", col), value);
Define and throw a dedicated exception instead of using a generic one.
import org.apache.accumulo.core.util.NamingThreadFactory; new NamingThreadFactory("Accumulo scanner read ahead thread"));
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.
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { final String tableName = OptUtil.getTableOpt(cl, shellState); if (!shellState.getConnector().instanceOperations().testClassLoad(constraint, Constraint.class.getName())) { } for (Entry<String,Integer> property : shellState.getConnector().tableOperations().listConstraints(tableName).entrySet()) { } final Options o = new Options();
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
if (verbose) System.out.println(msg); if (zapMaster) ZooReaderWriter.getInstance().recursiveDelete(tserversPath + "/" + child, NodeMissingPolicy.SKIP);
Remove this call to "exit" or ensure it is really required.
if (!Arrays.equals(value, zero)) throw new Exception("Bad key at " + entry);
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. */
Replace all tab characters in this file by sequences of white-spaces.
package org.apache.accumulo.examples.simple.mapreduce.bulk;
Rename "table" which hides the field declared at line 107.
String[] tableNames = getTableNames(2); String table1 = tableNames[0]; String table2 = tableNames[1];
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.util.UUID; import org.apache.accumulo.core.tabletserver.thrift.LogCopyInfo; import org.apache.accumulo.server.ServerConstants; import org.apache.hadoop.fs.Path; private String ephemeralNode; // call before putting this service online removeIncompleteCopies(acuConf, fs, rootDirs); /** * @param acuConf * @param fs * @param rootDirs * @throws IOException */ private void removeIncompleteCopies(AccumuloConfiguration acuConf, FileSystem fs, Set<String> rootDirs) throws IOException { if (acuConf.getBoolean(Property.MASTER_RECOVERY_SORT_MAPREDUCE)) { return; } Set<String> walogs = new HashSet<String>(); for (String root : rootDirs) { File rootFile = new File(root); for (File walog : rootFile.listFiles()) { try { UUID.fromString(walog.getName()); walogs.add(walog.getName()); } catch (IllegalArgumentException iea) { LOG.debug("Ignoring " + walog.getName()); } } } // look for .recovered that are not finished for (String walog : walogs) { Path path = new Path(ServerConstants.getRecoveryDir() + "/" + walog + ".recovered"); if (fs.exists(path) && !fs.exists(new Path(path, "finished"))) { LOG.debug("Incomplete copy/sort in dfs, deleting " + path); fs.delete(path, true); } } } ephemeralNode = path; public LogCopyInfo startCopy(TInfo info, AuthInfo credentials, String localLog, String fullyQualifiedFileName, boolean sort) throws ThriftSecurityException, LogCopyInfo lci = writer.startCopy(null, credentials, localLog, fullyQualifiedFileName, sort); lci.loggerZNode = ephemeralNode; return lci;
Either log or rethrow this exception.
@Deprecated
Remove this unused method parameter "ex".
package org.apache.accumulo.examples.wikisearch.ingest; import java.util.LinkedHashMap; import java.util.Map; public class LRUOutputCombiner<Key,Value> extends LinkedHashMap<Key,Value> { private static final long serialVersionUID = 1L; public static abstract class Fold <Value> { public abstract Value fold(Value oldValue, Value newValue); } public static abstract class Output<Key,Value> { public abstract void output(Key key, Value value); } private final int capacity; private final Fold<Value> fold; private final Output<Key,Value> output; private long cacheHits = 0; private long cacheMisses = 0; public LRUOutputCombiner(int capacity, Fold<Value> fold, Output<Key,Value> output) { super(capacity + 1, 1.1f, true); this.capacity = capacity; this.fold = fold; this.output = output; } protected boolean removeEldestEntry(Map.Entry<Key,Value> eldest) { if (size() > capacity) { output.output(eldest.getKey(), eldest.getValue()); return true; } return false; } @Override public Value put(Key key, Value value) { Value val = get(key); if (val != null) { value = fold.fold(val, value); cacheHits++; } else { cacheMisses++; } super.put(key, value); return null; } public void flush() { for (Map.Entry<Key,Value> e : entrySet()) { output.output(e.getKey(), e.getValue()); } clear(); } }
Introduce a new variable instead of reusing the parameter "value".
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
1 duplicated blocks of code must be removed.
import org.apache.accumulo.core.client.BatchWriterConfig; final BatchWriter bw = shellState.getConnector().createBatchWriter(shellState.getTableName(), new BatchWriterConfig().setMaxMemory(m.estimatedMemoryUsed()).setMaxWriteThreads(1));
Remove this unused method parameter "e".
/* * 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.
* Autogenerated by Thrift Compiler (0.9.0) import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; public static class checkTrace<I extends Iface> extends org.apache.thrift.ProcessFunction<I, checkTrace_args> { public checkTrace_args getEmptyArgsInstance() { protected boolean isOneway() { return false; } public checkTrace_result getResult(I iface, checkTrace_args args) throws org.apache.thrift.TException { @SuppressWarnings("all") public enum _Fields implements org.apache.thrift.TFieldIdEnum { // check for sub-struct validity if (tinfo != null) { tinfo.validate(); } @SuppressWarnings("all") public enum _Fields implements org.apache.thrift.TFieldIdEnum { private byte __isset_bitfield = 0; __isset_bitfield = other.__isset_bitfield; __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID); return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID); __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value); // check for sub-struct validity // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; if (struct.isSetSuccess()) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); oprot.writeBool(struct.success); oprot.writeFieldEnd(); }
Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.
locCols.add(new Column(TextUtil.getBytes(MetadataTable.CURRENT_LOCATION_COLUMN_FAMILY), null, null)); locCols.add(MetadataTable.PREV_ROW_COLUMN.toColumn());
Use "Long.toString" instead.
import org.apache.accumulo.core.zookeeper.ZooUtil; return new ZooKeeperInstance(UUID.fromString(ZooUtil.getInstanceIDFromHdfs(instanceDir)), keepers);
Immediately return this expression instead of assigning it to the temporary variable "result".
* 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. */ long sum = 0; public Value aggregate() { return new Value(Long.toString(sum).getBytes()); } public void collect(Value value) { sum += Long.parseLong(new String(value.get())); } public void reset() { sum = 0; }
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.
import org.apache.hadoop.fs.Path;
Remove this unused import 'org.apache.hadoop.fs.Path'.
if (!shellState.getConnector().tableOperations().exists(tableName)) throw new TableNotFoundException(null, tableName, null);
Remove this call to "exit" or ensure it is really required.
package org.apache.accumulo.core.iterators.user; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.IteratorUtil; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.iterators.SortedMapIterator; import org.apache.accumulo.core.iterators.user.RowDeletingIterator;
Remove the literal "false" boolean value.
import org.apache.log4j.Logger;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
package org.apache.accumulo.examples.wikisearch.parser; import org.apache.accumulo.examples.wikisearch.parser.QueryParser.QueryTerm; import org.apache.accumulo.examples.wikisearch.parser.RangeCalculator.RangeBounds;
Rename "table" which hides the field declared at line 107.
import java.nio.charset.Charset; private static final Charset utf8 = Charset.forName("UTF8"); Connector conn = instance.getConnector(user, passw.getBytes(utf8)); new AuthInfo(user, ByteBuffer.wrap(pass.getBytes(utf8)), HdfsZooInstance.getInstance().getInstanceID()), table, false, locations, tablets); checkTabletServer(conf, user, ByteBuffer.wrap(pass.getBytes(utf8)), entry, failures);
Move this variable to comply with Java Code Conventions.
String msg = "Must set dfs.durable.sync OR dfs.support.append to true. Which one needs to be set depends on your version of HDFS. See ACCUMULO-623. \n"+ "HADOOP RELEASE VERSION SYNC NAME DEFAULT\n"+ "Apache Hadoop 0.20.205 dfs.support.append false\n"+ "Apache Hadoop 0.23.x dfs.support.append true\n"+ "Apache Hadoop 1.0.x dfs.support.append false\n"+ "Apache Hadoop 1.1.x dfs.durable.sync true\n"+ "Apache Hadoop 2.0.0-2.0.2 dfs.support.append true\n"+ "Cloudera CDH 3u0-3u3 ???? true\n"+ "Cloudera CDH 3u4 dfs.support.append true\n"+ "Hortonworks HDP `1.0 dfs.support.append false\n"+ "Hortonworks HDP `1.1 dfs.support.append false";
Replace all tab characters in this file by sequences of white-spaces.
* Autogenerated by Thrift Compiler (0.9.0) import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; private byte __isset_bitfield = 0; __isset_bitfield = other.__isset_bitfield; __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __VIOLATIONCODE_ISSET_ID); return EncodingUtils.testBit(__isset_bitfield, __VIOLATIONCODE_ISSET_ID); __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __VIOLATIONCODE_ISSET_ID, value); __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __NUMBEROFVIOLATINGMUTATIONS_ISSET_ID); return EncodingUtils.testBit(__isset_bitfield, __NUMBEROFVIOLATINGMUTATIONS_ISSET_ID); __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __NUMBEROFVIOLATINGMUTATIONS_ISSET_ID, value); // check for sub-struct validity __isset_bitfield = 0;
Rename this class name to match the regular expression '^[A-Z][a-zA-Z0-9]*$'.
.println("Usage: bin/tool.sh accumulo-examplesjar accumulo.examples.helloworld.InsertWithBatchWriter <instance name> <zoo keepers> <username> <password> <tableName>"); String user = args[2]; byte[] pass = args[3].getBytes(); String tableName = args[4];
Move this variable to comply with Java Code Conventions.
import java.nio.charset.Charset; private static final Charset utf8 = Charset.forName("UTF8"); byte[] lockContent = new ServerServices(getClientAddressString(), Service.TSERV_CLIENT).toString().getBytes(utf8);
Move this variable to comply with Java Code Conventions.
if (cl.getArgs()[0].equalsIgnoreCase("on")) Shell.setDebugging(true); else if (cl.getArgs()[0].equalsIgnoreCase("off")) Shell.setDebugging(false); else throw new BadArgumentException("Argument must be 'on' or 'off'", fullCommand, fullCommand.indexOf(cl.getArgs()[0]));
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.client.BatchWriterConfig; BatchWriter bw = getConnector().createBatchWriter("ct", new BatchWriterConfig()); bw = getConnector().createBatchWriter("ct", new BatchWriterConfig()); bw = getConnector().createBatchWriter("ct", new BatchWriterConfig()); bw = getConnector().createBatchWriter("ct", new BatchWriterConfig()); bw = getConnector().createBatchWriter("ct", new BatchWriterConfig()); BatchWriter bw = getConnector().createBatchWriter(table, new BatchWriterConfig()); bw = getConnector().createBatchWriter(table, new BatchWriterConfig());
Remove this unused method parameter "e".
import org.apache.accumulo.core.security.thrift.Credentials; public void initializeSecurity(Credentials credentials, String principal, byte[] token) throws AccumuloSecurityException { zoo.putPersistentData(ZKUserPath, principal.getBytes(), NodeExistsPolicy.FAIL); constructUser(principal, ZKSecurityTool.createPass(token)); public void createUser(String principal, byte[] token) throws AccumuloSecurityException { constructUser(principal, ZKSecurityTool.createPass(token)); throw new AccumuloSecurityException(principal, SecurityErrorCode.USER_EXISTS, e); throw new AccumuloSecurityException(principal, SecurityErrorCode.CONNECTION_ERROR, e); throw new AccumuloSecurityException(principal, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e); public void changePassword(String principal, byte[] token) throws AccumuloSecurityException { if (userExists(principal)) { zooCache.clear(ZKUserPath + "/" + principal); ZooReaderWriter.getRetryingInstance().putPrivatePersistentData(ZKUserPath + "/" + principal, ZKSecurityTool.createPass(token), NodeExistsPolicy.OVERWRITE); throw new AccumuloSecurityException(principal, SecurityErrorCode.CONNECTION_ERROR, e); throw new AccumuloSecurityException(principal, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e); throw new AccumuloSecurityException(principal, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist public boolean authenticateUser(String principal, byte[] token) throws AccumuloSecurityException { String zpath = ZKUserPath + "/" + principal; boolean result = ZKSecurityTool.checkPass(token, pass); result = ZKSecurityTool.checkPass(token, pass); public String getAuthorizorName() { return this.getClass().getCanonicalName();
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
// TODO: do something better than poll - ACCUMULO-1310
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".
import org.apache.accumulo.fate.Repo;
Remove this call to "exit" or ensure it is really required.
switch (ae.getSecurityErrorCode()) { switch (ae.getSecurityErrorCode()) { switch (ae.getSecurityErrorCode()) {
Do not forget to remove this deprecated code someday.
} finally {
Refactor this code to not nest more than 3 if/for/while/switch/try statements.
@SuppressWarnings("all") public class MutationLogger {
13 duplicated blocks of code must be removed.
private static final Logger log = Logger.getLogger(ZooStore.class); String basePath; ZooCache cache = new ZooCache(); public ZooStore(String basePath) throws IOException { if (basePath.endsWith("/")) basePath = basePath.substring(0, basePath.length() - 1); this.basePath = basePath; } public ZooStore() throws IOException { this(ZooUtil.getRoot(HdfsZooInstance.getInstance().getInstanceID())); } @Override public byte[] get(String path) throws DistributedStoreException { try { return cache.get(relative(path)); } catch (Exception ex) { throw new DistributedStoreException(ex); } private String relative(String path) { return basePath + path; } @Override public List<String> getChildren(String path) throws DistributedStoreException { try { return cache.getChildren(relative(path)); } catch (Exception ex) { throw new DistributedStoreException(ex); } @Override public void put(String path, byte[] bs) throws DistributedStoreException { try { path = relative(path); ZooReaderWriter.getInstance().putPersistentData(path, bs, NodeExistsPolicy.OVERWRITE); cache.clear(); log.debug("Wrote " + new String(bs) + " to " + path); } catch (Exception ex) { throw new DistributedStoreException(ex); } @Override public void remove(String path) throws DistributedStoreException { try { log.debug("Removing " + path); path = relative(path); ZooReaderWriter zoo = ZooReaderWriter.getInstance(); if (zoo.exists(path)) zoo.recursiveDelete(path, NodeMissingPolicy.SKIP); cache.clear(); } catch (Exception ex) { throw new DistributedStoreException(ex); }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
@Test(timeout = 30 * 1000)
Either log or rethrow this exception.
import org.apache.accumulo.server.iterators.MetadataBulkLoadFilter; TablePropUtil.setTableProperty(Constants.METADATA_TABLE_ID, Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.bulkLoadFilter", "20," + MetadataBulkLoadFilter.class.getName());
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.
import org.junit.Assert;
Remove this unused private "appendProp" 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. */ @SuppressWarnings("all") public enum TableOperationExceptionType implements org.apache.thrift.TEnum {
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
return FileOutputConfigurator.getAccumuloConfiguration(CLASS, InputFormatBase.getConfiguration(context)); final Configuration conf = InputFormatBase.getConfiguration(context);
Define and throw a dedicated exception instead of using a generic one.
import org.apache.accumulo.proxy.thrift.UserPass; protected static ByteBuffer userpass; userpass = tpc.proxy.login(new UserPass("root", ByteBuffer.wrap("".getBytes())));
Immediately return this expression instead of assigning it to the temporary variable "connector".
import org.apache.accumulo.core.client.admin.InstanceOperationsImpl; instanceops = new InstanceOperationsImpl(instance, credentials);
Either log or rethrow this exception.
System.out.printf("SCN %d %s %d %d%n", t1, new String(scanStart), (t2 - t1), count);
Use isEmpty() to check whether the collection is empty or not.
package org.apache.accumulo.cloudtrace.instrument;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.client.security.SecurityErrorCode; if (ae.getSecurityErrorCode().equals(SecurityErrorCode.USER_DOESNT_EXIST)) { if (ae.getSecurityErrorCode().equals(SecurityErrorCode.USER_DOESNT_EXIST)) { } else if (ae.getSecurityErrorCode().equals(SecurityErrorCode.TABLE_DOESNT_EXIST)) {
Do not forget to remove this deprecated code someday.
try { TimestampFilter.setStart(is, 253402300800001l, true); assertTrue(false); } catch (Exception e) {} try { TimestampFilter.setEnd(is, 253402300800001l, true); assertTrue(false); } catch (Exception e) {}
Either log or rethrow this exception.
if (currentBatch.size() == 0) continue; if (finished) return false; if (obj instanceof RuntimeException) throw (RuntimeException) obj; else throw new RuntimeException((Exception) obj); if (hasNext()) return iter.next();
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.server.monitor.Monitor; AccumuloConfiguration conf = Monitor.getSystemConfiguration();
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.util.HashMap; import java.util.Set; import java.util.Map.Entry; import org.apache.accumulo.core.cli.BatchWriterOpts; import org.apache.accumulo.core.cli.ClientOnRequiredTable; import org.apache.accumulo.core.security.thrift.SecurityErrorCode; import com.beust.jcommander.Parameter; static class Opts extends ClientOnRequiredTable { @Parameter(names="--num", required=true) int num = 0; @Parameter(names="--min") long min = 0; @Parameter(names="--max") long max = Long.MAX_VALUE; @Parameter(names="--size", required=true, description="size of the value to write") int size = 0; @Parameter(names="--vis", converter=VisibilityConverter.class) ColumnVisibility visiblity = new ColumnVisibility(""); @Parameter(names="--seed", description="seed for pseudo-random number generator") Long seed = null; } Opts opts = new Opts(); BatchWriterOpts bwOpts = new BatchWriterOpts(); opts.parseArgs(RandomBatchWriter.class.getName(), args, bwOpts); if (opts.seed == null) r = new Random(opts.seed); Connector connector = opts.getConnector(); BatchWriter bw = connector.createBatchWriter(opts.tableName, bwOpts.getBatchWriterConfig()); ColumnVisibility cv = opts.visiblity; for (int i = 0; i < opts.num; i++) { long rowid = (Math.abs(r.nextLong()) % (opts.max - opts.min)) + opts.min; Mutation m = createMutation(rowid, opts.size, cv); HashMap<String,Set<SecurityErrorCode>> tables = new HashMap<String,Set<SecurityErrorCode>>(); for (Entry<KeyExtent,Set<SecurityErrorCode>> ke : e.getAuthorizationFailures().entrySet()) { Set<SecurityErrorCode> secCodes = tables.get(ke.getKey().getTableId().toString()); if (secCodes == null) { secCodes = new HashSet<SecurityErrorCode>(); tables.put(ke.getKey().getTableId().toString(), secCodes); } secCodes.addAll(ke.getValue());
Remove this unused private "appendProp" method.
import java.util.Arrays; import org.apache.accumulo.core.security.thrift.SecurityErrorCode; if (!acu.users.containsKey(user)) conn.securityOperations().createUser(user, pass, new Authorizations()); else if (!Arrays.equals(acu.users.get(user).password, pass)) throw new AccumuloSecurityException(user, SecurityErrorCode.BAD_CREDENTIALS);
Return empty string instead.
client2.nextK(scanner, 10); client2.closeScanner(scanner); client.nextK(scanner, 100); client.nextK(scanner, 10); client.closeScanner(scanner); client.nextK(scanner, 100); ScanResult more = client.nextK(scanner, 2); client.closeScanner(scanner); more = client.nextK(scanner, 2); client.closeScanner(scanner); more = client.nextK(scanner, 100); client.closeScanner(scanner); more = client.nextK(scanner, 100); client.closeScanner(scanner); more = client.nextK(scanner, 100); client.closeScanner(scanner); more = client.nextK(scanner, 100); client.closeScanner(scanner); ScanResult more = client.nextK(scanner, 100);
Either log or rethrow this exception.
* Returns an iterator over an accumulo table. This iterator uses the options that are currently set for its lifetime. So setting options will have no effect
2 duplicated blocks of code must be removed.
for (int threads: new int[]{1, 2, 16, 64, 256} ) {
Return empty string instead.
package org.apache.accumulo.server.master.state.tables; import java.util.Map; import org.apache.accumulo.core.master.state.tables.TableState; public interface TableObserver { void initialize(Map<String, TableState> tableIdToStateMap); void stateChanged(String tableId, TableState tState); void sessionExpired(); }
Return empty string instead.
Long next = iter.next(); sum = safeAdd(sum, next);
Remove this unused private "appendProp" method.
import static org.junit.Assert.*; cfg.setNumTservers(1); @Test(timeout = 60 * 1000) final int TABLES = 15; c.instanceOperations().setProperty(Property.TSERV_MAJC_MAXCONCURRENT.getKey(), "5"); for (int i = 1; i < TABLES; i++) c.tableOperations().clone("test_ingest", "test_ingest" + i, true, null, null); UtilWaitThread.sleep(11*1000); // time between checks of the thread pool sizes for (int i = 1; i < TABLES; i++) for (int i = 0; i < 30; i++) { int count = 0; if (count > 3) return; fail("Could not observe higher number of threads after changing the config");
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
range.add(new Text(String.format("%016x", rand.nextLong() & 0x7fffffffffffffffl))); range.add(new Text(String.format("%016x", rand.nextLong() & 0x7fffffffffffffffl)));
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.tokens.AccumuloToken; import org.apache.accumulo.core.security.tokens.UserPassToken; import org.apache.accumulo.core.util.ByteBufferUtil; * @deprecated Use {@link #createUser(AccumuloToken)} instead createUser(new UserPassToken(user, password), authorizations); /** * @deprecated @since 1.5, use {@link #createUser(AccumuloToken)} * @param user * @param password * @throws AccumuloException * @throws AccumuloSecurityException */ public void createUser(AccumuloToken<?,?> token, Authorizations authorization) throws AccumuloException, AccumuloSecurityException { if (token instanceof UserPassToken) { UserPassToken upt = (UserPassToken) token; this.acu.users.put(upt.getPrincipal(), new MockUser(upt.getPrincipal(), upt.getPassword(), authorization)); } else throw new AccumuloSecurityException(token.getPrincipal(), SecurityErrorCode.INVALID_TOKEN); } @Override public void createUser(AccumuloToken<?,?> token) throws AccumuloException, AccumuloSecurityException { createUser(token, new Authorizations()); } @Override /** * @deprecated @since 1.5, use {@link #changeUserPassword(AccumuloToken)} */ changeUserPassword(new UserPassToken(name, password)); } @Override public void changeUserPassword(AccumuloToken<?,?> token) throws AccumuloException, AccumuloSecurityException { MockUser user = acu.users.get(token.getPrincipal()); if (user != null){ if (token instanceof UserPassToken) { UserPassToken upt = (UserPassToken) token; // want to copy the password user.password = ByteBufferUtil.toBytes(upt.password); } else throw new AccumuloSecurityException(token.getPrincipal(), SecurityErrorCode.INVALID_TOKEN); } throw new AccumuloSecurityException(token.getPrincipal(), SecurityErrorCode.USER_DOESNT_EXIST);
Immediately return this expression instead of assigning it to the temporary variable "ret".
/** * 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.zookeeper; import org.apache.accumulo.fate.zookeeper.ZooReader; import org.apache.zookeeper.Watcher; /** * This class remains here for backwards compatibility. * * @deprecated since 1.5, replaced by {@link org.apache.accumulo.fate.zookeeper.ZooCache} */ public class ZooCache extends org.apache.accumulo.fate.zookeeper.ZooCache { public ZooCache(String zooKeepers, int sessionTimeout) { super(zooKeepers, sessionTimeout); } public ZooCache(String zooKeepers, int sessionTimeout, Watcher watcher) { super(zooKeepers, sessionTimeout, watcher); } public ZooCache(ZooReader reader, Watcher watcher) { super(reader, watcher); } }
Remove this call to "exit" or ensure it is really required.
package org.apache.accumulo.examples.simple.mapreduce;
Rename "table" which hides the field declared at line 107.
if (data.elapsed < 0 || data.sumDev < 0 || data.queueSumDev < 0 || data.queueTime < 0) resetTimes(); if (data.elapsed < 0 || data.sumDev < 0 || data.queueSumDev < 0 || data.queueTime < 0) resetTimes();
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.iterators.system.ColumnFamilySkippingIterator; ColumnFamilySkippingIterator cfsi = new ColumnFamilySkippingIterator(delIter); ColumnQualifierFilter colFilter = new ColumnQualifierFilter(cfsi, columns);
Use "Integer.toString" instead.
if (shellState.getTableName().equals(cl.getArgs()[0])) shellState.setTableName(cl.getArgs()[1]);
Remove this call to "exit" or ensure it is really required.
AccumuloOutputFormat.setZooKeeperInstance(job.getConfiguration(), args[0], args[1]); AccumuloOutputFormat.setOutputInfo(job.getConfiguration(), args[2], args[3].getBytes(), true, args[6]);
This block of commented-out lines of code should be removed.
import com.google.common.net.HostAndPort; TServerInstance someTServer = new TServerInstance(HostAndPort.fromParts("127.0.0.1", 1234), 0x123456);
Remove this unused method parameter "threadName".
public static byte[] getBytes(Text text) { byte[] bytes = text.getBytes(); if (bytes.length != text.getLength()) { bytes = new byte[text.getLength()]; System.arraycopy(text.getBytes(), 0, bytes, 0, bytes.length); return bytes; } public static ByteBuffer getByteBuffer(Text text) { if (text == null) return null; byte[] bytes = text.getBytes(); return ByteBuffer.wrap(bytes, 0, text.getLength()); } public static Text truncate(Text text, int maxLen) { if (text.getLength() > maxLen) { Text newText = new Text(); newText.append(text.getBytes(), 0, maxLen); String suffix = "... TRUNCATED"; newText.append(suffix.getBytes(), 0, suffix.length()); return newText; return text; } public static Text truncate(Text row) { return truncate(row, Constants.MAX_DATA_TO_PRINT); }
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. */ package org.apache.accumulo.server.test.continuous; /** * */ public class GenSplits { public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: " + GenSplits.class.getName() + " <num tablets>"); System.exit(-1); } int numTablets = Integer.parseInt(args[0]); if (numTablets < 1) { System.err.println("ERROR: numTablets < 1"); System.exit(-1); } int numSplits = numTablets - 1; long distance = (Long.MAX_VALUE / numTablets) + 1; long split = distance; for (int i = 0; i < numSplits; i++) { String s = String.format("%016x", split); while (s.charAt(s.length() - 1) == '0') { s = s.substring(0, s.length() - 1); } System.out.println(s); split += distance; } } }
Replace this use of System.out or System.err by a logger.
public static class CountingIterator extends WrappingIterator { private ArrayList<CountingIterator> deepCopies; private AtomicLong entriesRead; this.deepCopies = other.deepCopies; this.entriesRead = other.entriesRead; deepCopies.add(this); public CountingIterator(SortedKeyValueIterator<Key,Value> source, AtomicLong entriesRead) { deepCopies = new ArrayList<Compactor.CountingIterator>(); this.entriesRead = entriesRead; long sum = 0; for (CountingIterator dc : deepCopies) { sum += dc.count; } return count + sum; CountingIterator citr = new CountingIterator(new MultiIterator(iters, extent.toDataRange()), entriesRead);
Move this constructor to comply with Java Code Conventions.
package org.apache.accumulo.examples.simple.mapreduce;
2 duplicated blocks of code must be removed.
splits.remove(ByteBuffer.wrap("c".getBytes()));
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.thrift.ThriftInstanceTokenWrapper; public void send(ThriftInstanceTokenWrapper credentials, String serverName, MasterClientService.Iface client) throws TException, ThriftSecurityException {
Immediately return this expression instead of assigning it to the temporary variable "ret".
import org.apache.accumulo.core.security.CredentialHelper; MetadataTable.updateTabletPrevEndRow(ke, CredentialHelper.create(opts.principal, opts.getToken(), opts.instance)); Writer t = MetadataTable.getMetadataTable(CredentialHelper.create(opts.principal, opts.getToken(), opts.instance));
Immediately return this expression instead of assigning it to the temporary variable "connector".
checkSplits(REG_TABLE_NAME, NUM_PRE_SPLITS/2, NUM_PRE_SPLITS * 2);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.nio.charset.Charset; private static final Charset utf8 = Charset.forName("UTF8"); byte[] version = Constants.VERSION.getBytes(utf8); byte[] inst = HdfsZooInstance.getInstance().getInstanceID().getBytes(utf8); versionFails = !Arrays.equals(buff, Constants.VERSION.getBytes(utf8)); instanceFails = !Arrays.equals(buff, HdfsZooInstance.getInstance().getInstanceID().getBytes(utf8)); md.update(Constants.VERSION.getBytes(utf8)); md.update(HdfsZooInstance.getInstance().getInstanceID().getBytes(utf8)); md.update(entry.getKey().getBytes(utf8)); md.update(entry.getValue().getBytes(utf8));
Move this variable to comply with Java Code Conventions.
* @deprecated since 1.4, replaced by {@link org.apache.accumulo.core.iterators.system.ColumnQualifierFilter}
Either log or rethrow this exception.
import org.apache.accumulo.fate.zookeeper.ZooReader; DistributedTrace.enable(instance, new ZooReader(instance.getZooKeepers(), instance.getZooKeepersSessionTimeOut()), "shell", InetAddress.getLocalHost() .getHostName());
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.conf.AccumuloConfiguration; static void startLogListener(AccumuloConfiguration conf) { new Daemon(new SocketServer(conf.getPort(Property.MONITOR_LOG4J_PORT))).start();
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
if (null != gcProcess) { result.put(ServerType.GARBAGE_COLLECTOR, references(gcProcess)); }
Define and throw a dedicated exception instead of using a generic one.
&& !SecurityHelper.getSysPerm(state, SecurityHelper.getSysUserName(state), SystemPermission.SYSTEM)) hasPermission = false; if (!success) for (int i = 0; i < password.length; i++) password[i]++; if (exists && hasPermission) throw new AccumuloException("Got a security exception when I should have had permission.", ae); else return; if (!hasPermission) throw new AccumuloException("Didn't get Security Exception when we should have"); if (result != (success && exists)) throw new AccumuloException("Got " + result + " as the result when it should be " + success);
Remove this call to "exit" or ensure it is really required.