Diff
stringlengths
10
2k
Message
stringlengths
28
159
/* * 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. */
Remove this unused private "appendProp" method.
public static void init(FileSystem fs, ServerConfiguration config, String application) throws UnknownHostException { for (Entry<String,String> entry : config.getConfiguration())
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
int counter = 0; @Override public int getPartition(LogFileKey key, LogFileValue value, int numPartitions) { // We don't really care if items with the same key stay together: we // just want a sort, with the load spread evenly over the reducers counter = ++counter % numPartitions; return counter; }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
TIteratorSetting _elem100; // optional TIteratorSetting _elem105; // optional
277 duplicated blocks of code must be removed.
import org.apache.accumulo.core.security.thrift.tokens.PasswordToken; import org.apache.accumulo.core.security.thrift.tokens.SecurityToken; this.acu.users.put(user, new MockUser(user, new PasswordToken().setPassword(password), authorizations)); public void createUser(String user, SecurityToken token) throws AccumuloException, AccumuloSecurityException { this.acu.users.put(user, new MockUser(user, token, new Authorizations())); return authenticateUser(name, new PasswordToken().setPassword(password)); } @Override public boolean authenticateUser(String name, SecurityToken token) throws AccumuloException, AccumuloSecurityException { return user.token.equals(token); public void changeLoginInfo(String name, SecurityToken token) throws AccumuloException, AccumuloSecurityException { user.token = token.clone(); public void changeUserPassword(String name, byte[] password) throws AccumuloException, AccumuloSecurityException { changeLoginInfo(name, new PasswordToken().setPassword(password)); } @Override
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.util.shell.Token; throw new BadArgumentException("Property cannot be modified in zookeeper", fullCommand, fullCommand.indexOf(property));
Define a constant instead of duplicating this literal "</div>\n" 8 times.
import org.apache.accumulo.cloudtrace.instrument.Tracer; client.update(Tracer.traceInfo(), rootCredentials, new KeyExtent(new Text("test_ingest"), null, new Text("row_0003750000")).toThrift(), mutation.toThrift());
Immediately return this expression instead of assigning it to the temporary variable "client".
import org.apache.accumulo.core.util.MetadataTable; Scanner scanner = state.getConnector().createScanner(MetadataTable.NAME, Authorizations.EMPTY); scanner.fetchColumnFamily(MetadataTable.CURRENT_LOCATION_COLUMN_FAMILY);
Use "Long.toString" instead.
* @deprecated since 1.4, replaced by {@link org.apache.accumulo.core.iterators.user.ColumnAgeOffFilter}
Either log or rethrow this exception.
public class TabletIT extends ConfigurableMacIT {
Use "Integer.toString" instead.
return new TabletServerBatchReaderIterator(instance, credentials, table, authorizations, ranges, numThreads, queryThreadPool, this, timeOut);
Move this constructor to comply with Java Code Conventions.
import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.server.client.HdfsZooInstance; private final FileSystem fs; private final AccumuloConfiguration conf; private List<SortedKeyValueIterator<Key,Value>> openMapFiles(Collection<String> files, FileSystem fs, AccumuloConfiguration conf) throws IOException { FileSKVIterator reader = FileOperations.getInstance().openReader(file, true, fs, fs.getConf(), conf); public OfflineMetadataScanner(AccumuloConfiguration conf, FileSystem fs) throws IOException { this.fs = fs; this.conf = conf; FileSystem fs = FileSystem.get(CachedConfiguration.getInstance()); ServerConfiguration conf = new ServerConfiguration(HdfsZooInstance.getInstance()); OfflineMetadataScanner scanner = new OfflineMetadataScanner(conf.getConfiguration(), fs);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
String[] tableNames = getTableNames(3); String tableName = tableNames[0]; String table2 = tableNames[1]; String table3 = tableNames[2];
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.trace.instrument.Trace;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
if (!shellState.getConnector().tableOperations().exists(tableName)) throw new TableNotFoundException(null, tableName, null); if (tableIterators == null) return; if (sa.length == 1) scanner.fetchColumnFamily(new Text(a)); else scanner.fetchColumn(new Text(sa[0]), new Text(sa[1]));
Remove this call to "exit" or ensure it is really required.
assertEquals(Authorizations.EMPTY, args.auths);
Remove this unused method parameter "range".
import org.apache.accumulo.fate.Repo;
Remove this call to "exit" or ensure it is really required.
private boolean jdwpEnabled = false; * @return is the current configuration in jdwpEnabled mode? public boolean isJDWPEnabled() { return jdwpEnabled; * @param jdwpEnabled * should the processes run remote jdwpEnabled servers? public MiniAccumuloConfig setJDWPEnabled(boolean jdwpEnabled) { this.jdwpEnabled = jdwpEnabled;
Define a constant instead of duplicating this literal "superSecret" 3 times.
COMPACT(13), IMPORT(14), EXPORT(15); case 14: return IMPORT; case 15: return EXPORT;
Rename this package name to match the regular expression '^[a-z]+(\.[a-z][a-z0-9]*)*$'.
package org.apache.accumulo.core.client.mock; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.Property; class MockConfiguration extends AccumuloConfiguration { Map<String, String> map; MockConfiguration(Map<String, String> settings) { map = settings; } public void put(String k, String v) { map.put(k, v); } @Override public String get(Property property) { return map.get(property.getKey()); } @Override public Iterator<Entry<String, String>> iterator() { return map.entrySet().iterator(); } }
Return empty string instead.
* Advances to the next K,V pair. Note that in minor compaction scope and in non-full major compaction scopes the iterator may see deletion entries. These * entries should be preserved by all iterators except ones that are strictly scan-time iterators that will never be configured for the minc or majc scopes. * Deletion entries are only removed during full major compactions. * Returns top key. Can be called 0 or more times without affecting behavior of next() or hasTop(). Note that in minor compaction scope and in non-full major * compaction scopes the iterator may see deletion entries. These entries should be preserved by all iterators except ones that are strictly scan-time * iterators that will never be configured for the minc or majc scopes. Deletion entries are only removed during full major compactions.
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.Constants; String auths = ""; ArrayList<String> argsList = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (args[i].equals("--auths")) { auths = args[++i]; } else { argsList.add(args[i]); } } args = argsList.toArray(new String[0]); Authorizations authorizations; if (auths == null || auths.trim().equals("")) authorizations = Constants.NO_AUTHS; else authorizations = new Authorizations(auths.split(",")); AccumuloInputFormat.setInputInfo(job.getConfiguration(), user, pass.getBytes(), clone, authorizations);
Remove this unused method parameter "r".
import java.nio.charset.Charset; private static final Charset utf8 = Charset.forName("UTF8"); Constants.METADATA_DIRECTORY_COLUMN.put(m, new Value(FastFormat.toZeroPaddedString(dirCount++, 8, 16, "/c-".getBytes(utf8)))); Constants.METADATA_DIRECTORY_COLUMN.put(m, new Value(FastFormat.toZeroPaddedString(dirCount++, 8, 16, "/c-".getBytes(utf8))));
Move this variable to comply with Java Code Conventions.
package org.apache.accumulo.server.tabletserver; import java.util.List; import org.apache.accumulo.core.data.KeyExtent; /** * A MemoryManager in accumulo currently determines when minor compactions * should occur and when ingest should be put on hold. The goal of a memory * manager implementation is to maximize ingest throughput and minimize the * number of minor compactions. * * * */ public interface MemoryManager { /** * An implementation of this function will be called periodically * by accumulo and should return a list of tablets to minor compact. * * Instructing a tablet that is already minor compacting (this can be * inferred from the TabletState) to minor compact has no effect. * * Holding all ingest does not affect metadata tablets. */ MemoryManagementActions getMemoryManagementActions(List<TabletState> tablets); /** * This method is called when a tablet is closed. A memory manger * can clean up any per tablet state it is keeping when this is * called. */ void tabletClosed(KeyExtent extent); }
Return empty string instead.
import org.apache.accumulo.core.security.Authorizations; BatchScanner bs = state.getConnector().createBatchScanner(indexTableName, Authorizations.EMPTY, 16); bs = state.getConnector().createBatchScanner(dataTableName, Authorizations.EMPTY, 16);
Remove this unused method parameter "range".
package org.apache.accumulo.examples.simple.dirlist; import org.apache.accumulo.examples.simple.filedata.FileDataIngest;
2 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. */ out.writeInt(mutations.length); for (int i = 0; i < mutations.length; i++) { mutations[i].write(out); } if (lfv.mutations.length == 0) return ""; builder.append(" " + new String(update.getColumnFamily()) + ":" + new String(update.getColumnQualifier()) + " " + (update.hasTimestamp() ? "[user]:" : "[system]:") + update.getTimestamp() + " [" + displayLabels(update.getColumnVisibility()) + "] " + (update.isDeleted() ? "<deleted>" : value) + "\n");
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.accumulo.proxy.thrift.PrincipalToken; protected static PrincipalToken userpass; userpass = new PrincipalToken("root", ByteBuffer.wrap("".getBytes()));
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
@Override public void close() {}
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation.
import org.apache.accumulo.core.cli.BatchWriterOpts; import org.apache.accumulo.core.cli.ClientOnRequiredTable; import org.apache.accumulo.core.cli.ScannerOpts; import com.beust.jcommander.Parameter; private Opts opts; private ScannerOpts scanOpts; private BatchWriterOpts bwOpts; m.put(QueryUtil.DIR_COLF, QueryUtil.COUNTS_COLQ, opts.visibility, countVal.toValue()); m.put(QueryUtil.DIR_COLF, QueryUtil.COUNTS_COLQ, opts.visibility, tmpCount.toValue()); FileCount(Opts opts, ScannerOpts scanOpts, BatchWriterOpts bwOpts) throws Exception { this.opts = opts; this.scanOpts = scanOpts; this.bwOpts = bwOpts; Connector conn = opts.getConnector(); Scanner scanner = conn.createScanner(opts.tableName, opts.auths); scanner.setBatchSize(scanOpts.scanBatchSize); BatchWriter bw = conn.createBatchWriter(opts.tableName, bwOpts.getBatchWriterConfig()); System.out.printf("Max depth : %d%n", depth); System.out.printf("Time to find max depth : %,d ms%n", (t2 - t1)); System.out.printf("Time to compute counts : %,d ms%n", (t3 - t2)); System.out.printf("Entries scanned : %,d %n", entriesScanned); System.out.printf("Counts inserted : %,d %n", inserts); } public static class Opts extends ClientOnRequiredTable { @Parameter(names="--vis", description="use a given visibility for the new counts", converter=VisibilityConverter.class) ColumnVisibility visibility = new ColumnVisibility(); Opts opts = new Opts(); ScannerOpts scanOpts = new ScannerOpts(); BatchWriterOpts bwOpts = new BatchWriterOpts(); String programName = FileCount.class.getName(); opts.parseArgs(programName, args, scanOpts, bwOpts); FileCount fileCount = new FileCount(opts, scanOpts, bwOpts);
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. */
Replace all tab characters in this file by sequences of white-spaces.
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 { 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;
Remove this unused method parameter "acuConf".
* 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. */ public StackOverflowException(String msg) { super(msg); } private static final long serialVersionUID = 1L;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
1 duplicated blocks of code must be removed.
package org.apache.accumulo.server.logger.metrics; public interface LogWriterMetricsMBean { public static final String close = "close"; public static final String copy = "copy"; public static final String create = "create"; public static final String logAppend = "logAppend"; public static final String logFlush = "logFlush"; public static final String logException = "logException"; public long getCloseCount(); public long getCloseAvgTime(); public long getCloseMinTime(); public long getCloseMaxTime(); public long getCopyCount(); public long getCopyAvgTime(); public long getCopyMinTime(); public long getCopyMaxTime(); public long getCreateCount(); public long getCreateMinTime(); public long getCreateMaxTime(); public long getCreateAvgTime(); public long getLogAppendCount(); public long getLogAppendMinTime(); public long getLogAppendMaxTime(); public long getLogAppendAvgTime(); public long getLogFlushCount(); public long getLogFlushMinTime(); public long getLogFlushMaxTime(); public long getLogFlushAvgTime(); public long getLogExceptionCount(); public void reset(); }
Return empty string instead.
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
1 duplicated blocks of code must be removed.
import java.util.Set; public static Map<TreeSet<String>,Long> getDiskUsage(AccumuloConfiguration acuConf, Set<String> tableIds, FileSystem fs, Connector conn, boolean humanReadable) throws IOException { Scanner mdScanner = null; try { mdScanner = conn.createScanner(Constants.METADATA_TABLE_NAME, Constants.NO_AUTHS); } catch (TableNotFoundException e) { throw new RuntimeException(e); } HashSet<String> tableIds = new HashSet<String>(); for (String tableName : tables) { String tableId = conn.tableOperations().tableIdMap().get(tableName); if (tableId == null) throw new TableNotFoundException(null, tableName, "Table " + tableName + " not found"); tableIds.add(tableId); } Map<TreeSet<String>,Long> usage = getDiskUsage(acuConf, tableIds, fs, conn, humanReadable);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
* @throws AccumuloSecurityException * @since 1.5.0 * @since 1.5.0 * @since 1.5.0 * @since 1.5.0
Move this constructor to comply with Java Code Conventions.
import org.apache.accumulo.core.util.MetadataTable; String scanner = client.createScanner(creds, MetadataTable.NAME, opt);
Use "Long.toString" instead.
/* * 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.
return Arrays.copyOfRange(buffer.array(), buffer.position(), buffer.limit());
This block of commented-out lines of code should 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.
import org.apache.accumulo.core.client.impl.thrift.SecurityErrorCode; TCredentials tCreds = new TCredentials(getPrincipal(), getToken().getClass().getName(), ByteBuffer.wrap(AuthenticationTokenSerializer.serialize(getToken())), instance.getInstanceID()); if (getToken().isDestroyed()) throw new RuntimeException("Token has been destroyed", new AccumuloSecurityException(getPrincipal(), SecurityErrorCode.TOKEN_EXPIRED)); return tCreds;
Either log or rethrow this exception.
this(instance, auths, range, state, MetadataTable.NAME); } MetaDataTableScanner(Instance instance, TCredentials auths, Range range, CurrentState state, String tableName) { mdScanner = connector.createBatchScanner(tableName, Authorizations.EMPTY, 8); this(instance, auths, range, MetadataTable.NAME); } public MetaDataTableScanner(Instance instance, TCredentials auths, Range range, String tableName) { this(instance, auths, range, null, tableName);
Reduce this switch case number of lines from 12 to at most 5, for example by extracting code into methods.
package org.apache.accumulo.cloudtrace.instrument.receivers; import org.apache.accumulo.cloudtrace.thrift.RemoteSpan; import org.apache.accumulo.cloudtrace.thrift.SpanReceiver.Client;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
* the shard table (created by {@link Index}) using the {@link IntersectingIterator}. * See docs/examples/README.shard for instructions.
1 duplicated blocks of code must be removed.
TabletServerStatus _elem24; // required String _elem31; // required DeadServer _elem34; // required TabletServerStatus _elem51; // required String _elem58; // required DeadServer _elem61; // required
Remove this unused method parameter "table".
import org.apache.accumulo.trace.instrument.thrift.TraceWrap; import org.apache.accumulo.trace.thrift.TInfo;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
/** * An input stream that reads file data stored in one or more Accumulo values. Used by {@link ChunkInputFormat} to present input streams to a mapper. */
Replace this use of System.out or System.err by a logger.
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { final String tableName = OptUtil.getTableOpt(cl, shellState); final Text startRow = OptUtil.getStartRow(cl); final Text endRow = OptUtil.getEndRow(cl); final Options o = new Options();
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.
Connector conn = state.getInstance().getConnector(WalkingSecurity.get(state).getSysUserName(), WalkingSecurity.get(state).getSysToken());
Immediately return this expression instead of assigning it to the temporary variable "connector".
import java.util.HashSet; public final class ZKAuthenticator implements Authenticator { public Set<Class<? extends AuthenticationToken>> getSupportedTokenTypes() { Set<Class<? extends AuthenticationToken>> cs = new HashSet<Class<? extends AuthenticationToken>>(); cs.add(PasswordToken.class); return cs;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
package org.apache.accumulo.server.test; import java.io.IOException; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.util.CachedConfiguration; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; public class BulkImportDirectory { public static void main(String[] args) throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException { if (args.length != 5) throw new RuntimeException("Usage: bin/accumulo " + BulkImportDirectory.class.getName() + " <username> <password> <tablename> <sourcedir> <failuredir>"); final String user = args[0]; final byte[] pass = args[1].getBytes(); final String tableName = args[2]; final String dir = args[3]; final String failureDir = args[4]; final Path failureDirPath = new Path(failureDir); final FileSystem fs = FileSystem.get(CachedConfiguration.getInstance()); fs.delete(failureDirPath, true); fs.mkdirs(failureDirPath); HdfsZooInstance.getInstance().getConnector(user, pass).tableOperations().importDirectory(tableName, dir, failureDir, false); } }
Return empty string instead.
Connector connector = instance.getConnector(CredentialHelper.create("user", new PasswordToken(new byte[0]), "foo")); Connector connector = instance.getConnector(CredentialHelper.create("user", new PasswordToken(new byte[0]), "foo")); Connector connector = instance.getConnector(CredentialHelper.create("user", new PasswordToken(new byte[0]), "foo"));
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.tokens.PasswordToken;
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.
private SimpleDateFormat simple; private int dateFormat; private int timeFormat; public DateTimeType(int dateFormat, int timeFormat) { this.dateFormat = dateFormat; this.timeFormat = timeFormat; this.simple = null; } public DateTimeType(SimpleDateFormat fmt) { simple = fmt; } @Override public String format(Object obj) { if (obj == null) return "-"; Long millis = (Long) obj; if (millis == 0) return "-"; if (simple != null) return simple.format(new Date(millis)).replace(" ", "&nbsp;"); return DateFormat.getDateTimeInstance(dateFormat, timeFormat, Locale.getDefault()).format(new Date(millis)).replace(" ", "&nbsp;"); } @Override public int compare(Long o1, Long o2) { if (o1 == null && o2 == null) return 0; else if (o1 == null) return -1; else return o1.compareTo(o2); } @Override public String alignment() { return "right"; }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.cli.ClientOnDefaultTable; import com.beust.jcommander.Parameter; import com.beust.jcommander.validators.PositiveInteger; static class Opts extends ClientOnDefaultTable { @Parameter(names="--output", description="location in HDFS to store the results; must not exist", required=true) String outputDir = "/tmp/continuousVerify"; @Parameter(names="--maxMappers", description="the maximum number of mappers to use", required=true, validateWith=PositiveInteger.class) int maxMaps = 0; @Parameter(names="--reducers", description="the number of reducers to use", required=true, validateWith=PositiveInteger.class) int reducers = 0; @Parameter(names="--offline", description="perform the verification directly on the files while the table is offline") boolean scanOffline = false; public Opts() { super("ci"); } } @Override public int run(String[] args) throws Exception { Opts opts = new Opts(); opts.parseArgs(this.getClass().getName(), args); String clone = opts.getTableName(); if (opts.scanOffline) { clone = opts.getTableName() + "_" + String.format("%016x", Math.abs(random.nextLong())); conn = opts.getConnector(); conn.tableOperations().clone(opts.getTableName(), clone, true, new HashMap<String,String>(), new HashSet<String>()); opts.setAccumuloConfigs(job); AccumuloInputFormat.setScanOffline(job.getConfiguration(), opts.scanOffline); Set<Range> ranges = opts.getConnector().tableOperations().splitRangeByTablets(opts.getTableName(), new Range(), opts.maxMaps); job.setNumReduceTasks(opts.reducers); job.getConfiguration().setBoolean("mapred.map.tasks.speculative.execution", opts.scanOffline); TextOutputFormat.setOutputPath(job, new Path(opts.outputDir)); if (opts.scanOffline) { opts.stopTracing();
Remove this unused private "appendProp" method.
package cloudtrace.instrument; import junit.framework.Assert; import org.junit.Test; public class CountSamplerTest { @Test public void testNext() { CountSampler half = new CountSampler(2); CountSampler hundred = new CountSampler(100); int halfCount = 0; int hundredCount = 0; for (int i = 0; i < 200; i++) { if (half.next()) halfCount++; if (hundred.next()) hundredCount++; } Assert.assertEquals(2, hundredCount); Assert.assertEquals(100, halfCount); } }
Return empty string instead.
} catch (MutationsRejectedException e) { logger.debug(e,e); return new org.apache.accumulo.proxy.thrift.MutationsRejectedException(e.toString()); public void cancelCompaction(ByteBuffer login, String tableName) throws TException {
Either log or rethrow this exception.
import org.apache.log4j.Logger; private static Logger log = Logger.getLogger(MetadataBulkLoadFilter.class); log.error(e, e);
Make the "log" logger private static final and rename it to comply with the format "LOG(?:GER)?".
t.setProperty("table", "table.iterator.minc.thirdName.opt.key", "value"); try { t.attachIterator("table", setting); Assert.fail(); } catch (IllegalArgumentException e) {} t.removeProperty("table", "table.iterator.minc.thirdName.opt.key");
Either log or rethrow this exception.
* * * * * * * * * * *
Replace all tab characters in this file by sequences of white-spaces.
/** * * @param key * @return true if this is a property whose value is expected to be a java class */ public static boolean isClassProperty(String key) { return (key.startsWith(Property.TABLE_CONSTRAINT_PREFIX.getKey()) && key.substring(Property.TABLE_CONSTRAINT_PREFIX.getKey().length()).split("\\.").length == 1) || (key.startsWith(Property.TABLE_ITERATOR_PREFIX.getKey()) && key.substring(Property.TABLE_ITERATOR_PREFIX.getKey().length()).split("\\.").length == 2) || key.equals(Property.TABLE_LOAD_BALANCER.getKey()); }
Rename this package name to match the regular expression '^[a-z]+(\.[a-z][a-z0-9]*)*$'.
@Test public void testDefaultMap() { DefaultMap<String,String> map = new DefaultMap<String,String>(""); map.put("key", "value"); String empty = map.get("otherKey"); assertEquals(map.get("key"), "value"); assertEquals(empty, ""); assertTrue(empty == map.get("otherKey")); }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
String[] volumes = instance.getConfiguration().get(Property.INSTANCE_VOLUMES).split(","); if (volumes.length > 1) { tablesDir = volumes[0] + tablesDir; } if (relFiles.contains(":")) { absFiles.add(relPath); } else { // handle old-style relative paths if (relPath.startsWith("..")) { absFiles.add(tablesDir + relPath.substring(2)); } else { absFiles.add(tablesDir + "/" + tableId + relPath); } }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
audit.log(Level.INFO, getDefaultPrompt() + input);
Remove this unused method parameter "range".
import java.nio.ByteBuffer; import org.apache.accumulo.core.security.thrift.AuthInfo; AuthInfo auth = getAuthInfo(); connector = new ZooKeeperInstance(instance, zookeepers).getConnector(auth); public AuthInfo getAuthInfo() { String username = props.getProperty("USERNAME"); String password = props.getProperty("PASSWORD"); String instance = props.getProperty("INSTANCE"); return new AuthInfo(username, ByteBuffer.wrap(password.getBytes()), instance); }
Reduce this switch case number of lines from 44 to at most 5, for example by extracting code into methods.
import org.apache.accumulo.core.security.tokens.NullToken; import org.apache.accumulo.core.security.tokens.SecurityToken;
Replace all tab characters in this file by sequences of white-spaces.
import org.apache.accumulo.core.util.MetadataTable; tablePerms.put(MetadataTable.ID, Collections.singleton(TablePermission.ALTER_TABLE));
Use "Long.toString" instead.
* A lexicoder for preserving the native Java sort order of Double values. *
Remove this unused import 'java.util.Date'.
/** * 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.client.lexicoder; import java.io.UnsupportedEncodingException; public class StringLexicoder implements Lexicoder<String> { @Override public byte[] encode(String data) { try { return data.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public String decode(byte[] data) { try { return new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
Rename this generic name to match the regular expression '^[A-Z]$'.
import org.apache.accumulo.core.security.thrift.Credentials; public OfflineIterator(ScannerOptions options, Instance instance, Credentials credentials, Authorizations authorizations, Text table, Range range) { conn = instance.getConnector(credentials.getPrincipal(), credentials.getToken()); private Credentials credentials; public OfflineScanner(Instance instance, Credentials credentials, String tableId, Authorizations authorizations) {
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
{ disableUnflaggedTableOptions(); }
Move the "y" string literal on the left side of this string comparison.
if (log.isTraceEnabled()) log.trace("Using existing connection to " + entry.getKey().getLocation() + ":" + entry.getKey().getPort()); if (log.isTraceEnabled()) log.trace("Using existing connection to " + cacheKey.getLocation() + ":" + cacheKey.getPort()); if (log.isTraceEnabled()) log.trace("Creating new connection to connection to " + cacheKey.getLocation() + ":" + cacheKey.getPort()); if (log.isTraceEnabled()) log.trace("Returned connection had error " + ctsc.getCacheKey()); if (ecount == null) ecount = 0l; if (log.isTraceEnabled()) log.trace("Returned connection " + ctsc.getCacheKey() + " ioCount : " + cachedConnection.transport.ioCount);
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.security.thrift.Credential; private Credential credentials; public ConnectorImpl(Instance instance, Credential cred) throws AccumuloException, AccumuloSecurityException { ArgumentChecker.notNull(instance, cred); this.credentials = cred; if (!cred.getPrincipal().equals("!SYSTEM")) { if (!iface.authenticateUser(Tracer.traceInfo(), credentials, credentials))
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
System.out.println("%n*** RUNNING TEST ***%n"); + " count: %,d cells time: %6.2f rate: %,6.2f cells/sec%n", count, time, count / time); System.out.printf("\tAggregate stats count: %,d cells time: %6.2f rate: %,6.2f cells/sec%n", count, time, count / time); System.out.printf("\t\tDescription: [%30s] average: %,6.2f std dev: %,6.2f min: %,d max: %,d %n", desc, s.getAverage(), s.getStdDev(), s.getMin(),
Use isEmpty() to check whether the collection is empty or not.
* Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * - Redistributions of source code must retain the above copyright * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * * *
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.
byte[] sb = s.getBytes();
Remove this unused method parameter "ex".
} else throw new ShellCommandException(ErrorCode.UNRECOGNIZED_COMMAND, getName());
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.trace.thrift.RemoteSpan;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
/* * 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.io.File; public static TemporaryFolder folder = new TemporaryFolder(new File(System.getProperty("user.dir") + "/target"));
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.util.Map.Entry; import java.util.Set; import org.apache.accumulo.core.security.thrift.SecurityErrorCode; 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 the redundant '!unknownSymbol!' thrown exception declaration(s).
* {@link Authenticator#login(String, Properties)} * @return Returns the corresponding Authenticator class, which can be used to create a token ({@link Authenticator#login(String, Properties)} or get a list of
Remove this unused method parameter "principal".
public abstract class InputFormatBase<K,V> extends AbstractInputFormat<K,V> { protected abstract static class RecordReaderBase<K,V> extends AbstractRecordReader<K,V> { @Override protected void setupIterators(JobConf job, Scanner scanner, String tableName) { setupIterators(job, scanner); } * the Hadoop job configuration protected void setupIterators(JobConf job, Scanner scanner) { List<IteratorSetting> iterators = getIterators(job); for (IteratorSetting iterator : iterators)
Either log or rethrow this exception.
import org.apache.accumulo.core.security.tokens.AuthenticationToken;
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.
/** * A Filter that matches entries whose timestamps fall within a range. */
Remove the literal "true" boolean value.
import org.apache.accumulo.cloudtrace.instrument.TraceExecutorService;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
shellState.getReader().println(); shellState.getReader().println(); shellState.getReader().println();
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. */ @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]*$'.
nextEvent.event("tablet %s was loaded on %s", tablet, serverName); nextEvent.event("tablet %s was unloaded from %s", tablet, serverName); if (tls.walogs.isEmpty() && tls.chopped) return TabletGoalState.UNASSIGNED; return TabletGoalState.HOSTED; mergeStats.update(tls.extent, state, tls.chopped, !tls.walogs.isEmpty());
The Cyclomatic Complexity of this method "update" is 13 which is greater than 10 authorized.
if (i == 10) continue; if (fs != null) fs.delete(new Path("manyMaps"), true); if (i == 10) continue; if (i == 10) continue;
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.data.PartialKey; Key startRange = new Key(fieldValue, fieldName); Range r = new Range(startRange, true, startRange.followingKey(PartialKey.ROW), true); Key startRange = new Key(fieldValue, fieldName); Range r = new Range(startRange, true, startRange.followingKey(PartialKey.ROW), true); Key startRange = new Key(new Text(normalizedFieldValue + "\u0000"), fieldName); Key endRange = new Key(new Text(normalizedFieldValue + "\u10FFFF"), fieldName); Range r = new Range(startRange, true, endRange, true); Key startRange = new Key(new Text(normalizedFieldValue + "\u0000"), fieldName); Key endRange = new Key(new Text(normalizedFieldValue + "\u10FFFF"), fieldName); Range r = new Range(startRange, true, endRange, true); Key startRange = new Key(lower, entry.getKey()); Key endRange = new Key(upper, entry.getKey()); Range r = new Range(startRange, true, endRange, true);
31 duplicated blocks of code must be removed.
@SuppressWarnings("all") public class TConstraintViolationSummary implements org.apache.thrift.TBase<TConstraintViolationSummary, TConstraintViolationSummary._Fields>, java.io.Serializable, Cloneable {
13 duplicated blocks of code must be removed.
// ensure last key in map is same as extent that was passed in return verifyTabletInformation(extent, instance, tabletsKeyValues, clientAddress, lock);
Define and throw a dedicated exception instead of using a generic one.