Diff
stringlengths
10
2k
Message
stringlengths
28
159
import org.apache.accumulo.core.cli.ClientOnRequiredTable; ClientOnRequiredTable opts = new ClientOnRequiredTable(); opts.parseArgs(InsertWithBatchWriter.class.getName(), args); Connector connector = opts.getConnector(); MultiTableBatchWriter mtbw = connector.createMultiTableBatchWriter(opts.getBatchWriterConfig()); if (!connector.tableOperations().exists(opts.tableName)) connector.tableOperations().create(opts.tableName); BatchWriter bw = mtbw.getBatchWriter(opts.tableName);
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.
opts.putAll(si.getOptions());
Refactor this code to not nest more than 3 if/for/while/switch/try statements.
import org.apache.accumulo.core.security.Authorizations; for (String table : new String[] {"bt1", "bt2", "bt3"}) { Scanner scanner = getConnector().createScanner("bt4", Authorizations.EMPTY); BatchScanner bs = getConnector().createBatchScanner(table, Authorizations.EMPTY, 3);
Remove this unused method parameter "range".
package org.apache.accumulo.core.client.admin; public enum ScanState { IDLE, RUNNING, QUEUED }
Return empty string 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. */ } } public synchronized Map<String,String> getLoggersFromZooKeeper() { HashMap<String,String> result = new HashMap<String,String>(); String[] loggers = {"1.2.3.4:1234", "1.1.1.2:1234", "1.1.1.3:1234",}; String[] update = {"1.2.3.4:1234"};
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.thrift.TCredentials; import org.apache.accumulo.core.security.tokens.AuthenticationToken; public void initializeSecurity(TCredentials credentials, String principal, byte[] token) throws AccumuloSecurityException { public void createUser(String principal, AuthenticationToken token) throws AccumuloSecurityException { public void changePassword(String principal, AuthenticationToken token) throws AccumuloSecurityException { public boolean authenticateUser(String principal, AuthenticationToken token) throws AccumuloSecurityException {
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
if (violations == null) violations = new Violations(); if (violations == null) violations = new Violations();
Remove this call to "exit" or ensure it is really required.
if (SecurityHelper.getSysPerm(state, SecurityHelper.getSysUserName(state), SystemPermission.CREATE_USER)) hasPermission = true; if (hasPermission) throw new AccumuloException("Got a security exception when I should have had permission.", ae); if (!exists) throw new AccumuloException("Got security exception when the user shouldn't have existed", ae); else return; if (!hasPermission) throw new AccumuloException("Didn't get Security Exception when we should have");
Remove this call to "exit" or ensure it is really required.
* @throws AccumuloSecurityException IteratorSetting vers = new IteratorSetting(1, "vers", VersioningIterator.class); try { VersioningIterator.setMaxVersions(vers, maxVersions); } catch (IllegalArgumentException e) { throw new IOException(e); } if ("vers".equals(setting.getName()) && 1 == setting.getPriority() && VersioningIterator.class.getName().equals(setting.getIteratorClass())) {
Either log or rethrow this exception.
StatType motion; StatType color; public enum StatType { osload, ingest, query } return "Server Activity"; String s = req.getParameter("shape"); if (s != null && (s.equals("square") || s.equals("squares"))) { s = req.getParameter("motion"); motion = StatType.ingest; if (s != null) { try { motion = StatType.valueOf(s); } catch (Exception e) {} } s = req.getParameter("color"); color = StatType.osload; if (s != null) { try { color = StatType.valueOf(s); } catch (Exception e) {} else if (size.equals("80")) spacing = 80; .append(spacing == 40 ? " selected='true'" : "").append(">40</option><option").append(spacing == 80 ? " selected='true'" : "") .append(">80</option></select></span>\n"); sb.append("&nbsp;&nbsp<span class='viscontrol'>Motion: <select id='motion' onchange='setMotion(this)'>"); addOptions(sb, motion); sb.append("</select></span>\n"); sb.append("&nbsp;&nbsp<span class='viscontrol'>Color: <select id='color' onchange='setColor(this)'>"); addOptions(sb, color); sb.append("</select></span>\n"); private void addOptions(StringBuilder sb, StatType selectedStatType) { for (StatType st : StatType.values()) { sb.append("<option").append(st.equals(selectedStatType) ? " selected='true'>" : ">").append(st).append("</option>"); } }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.io.FileNotFoundException; import org.apache.hadoop.fs.Trash; private Option optSafeMode, optOffline, optVerboseMode, optAddress, optNoTrash; private Trash trash = null; private boolean safemode, offline, verbose, noTrash; optNoTrash = new Option("t", "no-trash", false, "do not use hdfs trash if it is enabled"); opts.addOption(optNoTrash); noTrash = commandLine.hasOption(optNoTrash.getOpt()); public void init(FileSystem fs, Instance instance, AuthInfo credentials, AccumuloConfiguration conf) throws IOException { log.info("trash enabled: " + !noTrash); if (!noTrash) { this.trash = new Trash(fs, fs.getConf()); } private boolean moveToTrash(Path path) throws IOException { if (trash == null) return false; try { return trash.moveToTrash(path); } catch (FileNotFoundException ex) { return false; } } if (tabletDirs.length == 0) { Path p = new Path(ServerConstants.getTablesDir() + "/" + delTableId); if (!moveToTrash(p)) fs.delete(p, false); } if (moveToTrash(p) || fs.delete(p, true)) {
Either log or rethrow this exception.
* @deprecated since 1.4, replaced by {@link org.apache.accumulo.core.iterators.user.GrepIterator}
Either log or rethrow this exception.
/** * Exception to throw if an operation is attempted on a table that already exists. * */ private static final long serialVersionUID = 1L; /** * @param tableId * the internal id of the table that exists * @param tableName * the visible name of the table that exists * @param description * the specific reason why it failed */ public TableExistsException(String tableId, String tableName, String description) { super("Table" + (tableName != null && !tableName.isEmpty() ? " " + tableName : "") + (tableId != null && !tableId.isEmpty() ? " (Id=" + tableId + ")" : "") + " exists" + (description != null && !description.isEmpty() ? " (" + description + ")" : "")); } /** * @param tableId * the internal id of the table that exists * @param tableName * the visible name of the table that exists * @param description * the specific reason why it failed * @param cause * the exception that caused this failure */ public TableExistsException(String tableId, String tableName, String description, Throwable cause) { this(tableId, tableName, description); super.initCause(cause); } /** * @param e * constructs an exception from a thrift exception */ public TableExistsException(ThriftTableOperationException e) { this(e.getTableId(), e.getTableName(), e.getDescription(), e); }
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. */ public interface ClientExecReturn<T,C> {
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.thrift.SecurityErrorCode; import org.apache.accumulo.core.util.SimpleThreadPool; private Map<KeyExtent,Set<SecurityErrorCode>> authorizationFailures; authorizationFailures = new HashMap<KeyExtent,Set<SecurityErrorCode>>(); private void updateAuthorizationFailures(Set<KeyExtent> keySet, SecurityErrorCode code) { HashMap<KeyExtent, SecurityErrorCode> map = new HashMap<KeyExtent, SecurityErrorCode>(); for (KeyExtent ke : keySet) map.put(ke, code); updateAuthorizationFailures(map); } private void updateAuthorizationFailures(Map<KeyExtent,SecurityErrorCode> authorizationFailures) { for (KeyExtent ke : authorizationFailures.keySet()) mergeAuthorizationFailures(this.authorizationFailures, authorizationFailures); private void mergeAuthorizationFailures(Map<KeyExtent,Set<SecurityErrorCode>> source, Map<KeyExtent,SecurityErrorCode> addition) { for (Entry<KeyExtent,SecurityErrorCode> entry : addition.entrySet()) { Set<SecurityErrorCode> secs = source.get(entry.getKey()); if (secs == null) { secs = new HashSet<SecurityErrorCode>(); source.put(entry.getKey(), secs); } secs.add(entry.getValue()); } } throw new MutationsRejectedException(cvsList, new HashMap<KeyExtent,Set<SecurityErrorCode>>(authorizationFailures), serverSideErrors, unknownErrors, lastUnknownError); sendThreadPool = new SimpleThreadPool(numSendThreads, this.getClass().getName()); updateAuthorizationFailures(Collections.singletonMap(new KeyExtent(new Text(Constants.METADATA_TABLE_ID), null, null), e.getErrorCode())); AccumuloSecurityException, AccumuloServerException { updateAuthorizationFailures(tabMuts.keySet(), e.code);
Remove this unused private "appendProp" method.
int numHosts = in.readInt();
Remove this unused import 'java.io.DataOutput'.
if (children == null || children.size() == 0) { if (children == null || children.size() == 0) { if (children == null || children.size() == 0) { if (children == null || children.size() == 0) { if (children == null || children.size() == 0) { if (children == null || children.size() == 0) { if (children == null || children.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.
/* * 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 class UserPass implements org.apache.thrift.TBase<UserPass, UserPass._Fields>, java.io.Serializable, Cloneable { @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]*$'.
// No alternative api in hadoop 20
Define a constant instead of duplicating this literal "org.apache.accumulo.core.iterators.WholeRowIterator" 4 times.
/* * 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 void testSerialization() throws IOException { String[] hosts = new String[2]; FileSplit fSplit = new FileSplit(testPath, 1, 2, hosts); WikipediaInputSplit split = new WikipediaInputSplit(fSplit, 7); out.close(); String[] hosts2 = fSplit2.getLocations(); for (int i = 0; i < hosts.length; i++) { Assert.assertEquals(hosts[i], hosts2[i]);
Move this variable to comply with Java Code Conventions.
import org.apache.accumulo.core.util.format.Formatter; import org.apache.accumulo.core.util.interpret.ScanInterpreter; public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { Class<? extends Formatter> formatter = getFormatter(cl, tableName, shellState); ScanInterpreter interpeter = getInterpreter(cl, tableName, shellState); scanner.setRanges(Collections.singletonList(getRange(cl, interpeter))); fetchColumns(cl, scanner, interpeter); printRecords(cl, shellState, scanner, formatter);
Return empty string 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. */ import java.util.HashMap; import org.apache.accumulo.instamo.AccumuloApp; import org.apache.accumulo.test.MiniAccumuloCluster; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.rules.TemporaryFolder; /** * An example unit test that shows how to use MiniAccumuloCluster in a unit test */ public class ExampleAccumuloUnitTest { public static TemporaryFolder folder = new TemporaryFolder(); private static MiniAccumuloCluster accumulo; @BeforeClass public static void setupMiniCluster() throws Exception { folder.create(); accumulo = new MiniAccumuloCluster(folder.getRoot(), "superSecret", new HashMap<String,String>()); accumulo.start(); } @Test(timeout = 30000) public void test() throws Exception { AccumuloApp.run(accumulo.getInstanceName(), accumulo.getZookeepers(), "superSecret", new String[0]); } @AfterClass public static void tearDownMiniCluster() throws Exception { accumulo.stop(); folder.delete(); } }
Remove this unused method parameter "args".
import org.apache.accumulo.core.iterators.user.IntersectingIterator;
Remove this unused private "match" method.
private Map<String,String> tidToNameMap; public TableLinkType() { tidToNameMap = Tables.getIdToNameMap(HdfsZooInstance.getInstance()); } @Override public String format(Object obj) { if (obj == null) return "-"; String tableId = (String) obj; return String.format("<a href='/tables?t=%s'>%s</a>", tableId, displayName(tableId)); } private String displayName(String tableId) { if (tableId == null) return "-"; return Tables.getPrintableTableNameFromId(tidToNameMap, tableId); } @Override public int compare(String o1, String o2) { return displayName(o1).compareTo(displayName(o2)); } @Override public String alignment() { return "left"; }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.Authorizations; RowIterator iter = new RowIterator(new IsolatedScanner(conn.createScanner(tableName, Authorizations.EMPTY)));
Remove this unused method parameter "range".
import org.apache.accumulo.core.security.thrift.Credential; public void initializeSecurity(Credential credentials, String rootuser) throws AccumuloSecurityException, ThriftSecurityException;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
Version make(String version) { return new Version(version); } public void testOne() { Version v; v = make("abc-1.2.3-ugly"); assertTrue(v != null); assertTrue(v.getPackage().equals("abc")); assertTrue(v.getMajorVersion() == 1); assertTrue(v.getMinorVersion() == 2); assertTrue(v.getReleaseVersion() == 3); assertTrue(v.getEtcetera().equals("ugly")); v = make("3.2.1"); assertTrue(v.getPackage() == null); assertTrue(v.getMajorVersion() == 3); assertTrue(v.getMinorVersion() == 2); assertTrue(v.getReleaseVersion() == 1); assertTrue(v.getEtcetera() == null); v = make("55"); assertTrue(v.getPackage() == null); assertTrue(v.getMajorVersion() == 55); assertTrue(v.getMinorVersion() == 0); assertTrue(v.getReleaseVersion() == 0); assertTrue(v.getEtcetera() == null); v = make("7.1-beta"); assertTrue(v.getPackage() == null); assertTrue(v.getMajorVersion() == 7); assertTrue(v.getMinorVersion() == 1); assertTrue(v.getReleaseVersion() == 0); assertTrue(v.getEtcetera().equals("beta")); try { make("beta"); fail("Should have thrown an error"); } catch (IllegalArgumentException t) {} }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.thrift.SecurityErrorCode;
1 duplicated blocks of code must be removed.
import org.apache.accumulo.core.security.thrift.Credentials; Credentials auth; auth = WalkingSecurity.get(state).getSysCredentials(); auth = WalkingSecurity.get(state).getTabCredentials(); Connector conn = state.getInstance().getConnector(auth.getPrincipal(), auth.getToken()); conn.securityOperations().changeUserPassword(target, newPass); WalkingSecurity.get(state).changePassword(target, newPass);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.lang.reflect.Constructor; DistCp cp = newDistCp(); private DistCp newDistCp() { try { @SuppressWarnings("unchecked") Constructor<DistCp>[] constructors = (Constructor<DistCp>[]) DistCp.class.getConstructors(); for (Constructor<DistCp> constructor : constructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length > 1 && parameterTypes[0].equals(Configuration.class)) if (parameterTypes.length == 1) { return constructor.newInstance(new Configuration()); } else if (parameterTypes.length == 2) { return constructor.newInstance(new Configuration(), null); } } } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("Unexpected constructors for DistCp"); }
Define and throw a dedicated exception instead of using a generic one.
private short replication; GZIPOutputStream out = new GZIPOutputStream(dest.create(new Path(destDir, name + ".gz_tmp"), false, dest.getConf().getInt("io.file.buffer.size", 4096), replication == 0 ? dest.getDefaultReplication() : replication, dest.getDefaultBlockSize())); this.replication = (short) conf.getCount(Property.LOGGER_ARCHIVE_REPLICATION);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
if (key != null) assertEquals(key.getRow().toString(), new String(v.get()));
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.client.IteratorSetting; private static final String MAX_COLUMNS = "max_columns"; /** * A convenience method for setting the maximum number of columns to keep. * * @param is * IteratorSetting object to configure. * @param maxColumns * number of columns to keep. */ public static void setMaxColumns(IteratorSetting is, int maxColumns) { is.addOption(MAX_COLUMNS, Integer.toString(maxColumns)); }
Remove this unused method parameter "hasStart".
import org.apache.accumulo.core.client.security.SecurityErrorCode; if (ae.getSecurityErrorCode().equals(SecurityErrorCode.PERMISSION_DENIED)) { } else if (ae.getSecurityErrorCode().equals(SecurityErrorCode.BAD_CREDENTIALS)) {
Do not forget to remove this deprecated code someday.
int maxSleepTime = 1000 * 60 * 3; // 3 minutes
Use "Long.toString" instead.
import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader; AccumuloVFSClassLoader.printClassPath();
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
if (!shellState.getConnector().securityOperations().authenticateUser(currentUser, oldPassword.getBytes())) byte[] pass = password.getBytes();
Remove this unused method parameter "ex".
if (l > max) max = l;
Remove this call to "exit" or ensure it is really required.
@Parameter(names = "--output", description = "output directory", required = true) @Parameter(names = "--columns", description = "columns to extract, in cf:cq{,cf:cq,...} form") @Override AccumuloInputFormat.fetchColumns(job, columnsToFetch);
Return empty string instead.
import java.util.TimerTask; import org.apache.accumulo.server.util.time.SimpleTimer; static String cachedInstanceName = null; synchronized(BasicServlet.class) { // Learn our instance name asynchronously so we don't hang up if zookeeper is down if (cachedInstanceName == null) { SimpleTimer.getInstance().schedule(new TimerTask() { @Override public void run() { synchronized (BasicServlet.class) { if (cachedInstanceName == null) { cachedInstanceName = HdfsZooInstance.getInstance().getInstanceName(); } } } }, 1000); } } sb.append("<div id='subheader'>Instance&nbsp;Name:&nbsp;").append(cachedInstanceName)
Define and throw a dedicated exception instead of using a generic one.
validAuthChars['.'] = true; validAuthChars['/'] = true;
Either log or rethrow this exception.
gi.init(new SortedMapIterator(input), is.getOptions(), null); gi.init(new SortedMapIterator(input), is.getOptions(), null); gi.init(new SortedMapIterator(input), is.getOptions(), null);
Refactor this code to not nest more than 3 if/for/while/switch/try statements.
String tableName = OptUtil.getTableOpt(cl, shellState); colFams.add(new Text(family.getBytes(Shell.CHARSET)));
Either log or rethrow this exception.
connector.securityOperations().changeUserAuthorizations(opts.principal, AUTHS);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
public static void main(String[] args) throws IOException { int startRow = Integer.parseInt(args[0]); int numRows = Integer.parseInt(args[1]); String outputFile = args[2]; Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = FileSystem.get(conf); PrintStream out = new PrintStream(new BufferedOutputStream(fs.create(new Path(outputFile)))); for (int i = 0; i < numRows; i++) { out.println(String.format("row_%08d\tvalue_%08d", i + startRow, i + startRow)); out.close(); }
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. */ * A tablet is assigned to a tablet server at the given address as long as it is alive and well. When the tablet server is restarted, the instance information * it advertises will change. Therefore tablet assignments can be considered out-of-date if the tablet server instance information has been changed. private String session; private String cachedStringRepresentation; this(AddressUtil.parseAddress(address, Property.TSERV_CLIENTPORT), Long.toHexString(session)); this(AddressUtil.parseAddress(new String(address.get()), Property.TSERV_CLIENTPORT), session.toString()); m.put(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY, asColumnQualifier(), asMutationValue()); m.put(Constants.METADATA_FUTURE_LOCATION_COLUMN_FAMILY, asColumnQualifier(), asMutationValue()); m.put(Constants.METADATA_LAST_LOCATION_COLUMN_FAMILY, asColumnQualifier(), asMutationValue()); m.putDelete(Constants.METADATA_LAST_LOCATION_COLUMN_FAMILY, asColumnQualifier()); if (this == other) return 0;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
if (time == 0) return zero; if (time == 0) return String.format("%dms", ms); if (time == 0) return String.format("%ds" + space + "%dms", sec, ms); if (time == 0) return String.format("%dm" + space + "%ds", min, sec); if (time == 0) return String.format("%dh" + space + "%dm", hr, min); if (time == 0) return String.format("%dd" + space + "%dh", day, hr);
Remove this call to "exit" or ensure it is really required.
String tableName = getTableNames(1)[0]; String dir = rootPath() + "/bulk_test_diff_files_89723987592_" + getTableNames(1)[0]; FunctionalTestUtils.bulkImport(c, fs, tableName, dir);
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
package org.apache.accumulo.trace.instrument;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
/** * @deprecated Use {@link #handleBlockSize(Configuration)} instead */ handleBlockSize(job.getConfiguration()); } protected static void handleBlockSize(Configuration conf) { blockSize = (int) getInstance(conf).getConfiguration().getMemoryInBytes(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE); blockSize = getBlockSize(conf); /** * @deprecated Use {@link #setFileType(Configuration,String)} instead */ setFileType(job.getConfiguration(), type); } public static void setFileType(Configuration conf, String type) { conf.set(FILE_TYPE, type); /** * @deprecated Use {@link #setBlockSize(Configuration,int)} instead */ setBlockSize(job.getConfiguration(), blockSize); } public static void setBlockSize(Configuration conf, int blockSize) { conf.setInt(BLOCK_SIZE, blockSize); private static int getBlockSize(Configuration conf) { return conf.getInt(BLOCK_SIZE, * @deprecated since 1.4, use {@link #setBlockSize(Configuration, int)} to set block size no other configurations are used by OutputFormat setZooKeeperInstance(job.getConfiguration(), instanceName, zooKeepers); } /** * * @param conf * @param instanceName * @param zooKeepers * @deprecated since 1.4, use {@link #setBlockSize(Configuration, int)} to set block size no other configurations are used by OutputFormat */ public static void setZooKeeperInstance(Configuration conf, String instanceName, String zooKeepers) { * @deprecated since 1.4, use {@link #setBlockSize(Configuration, int)} no other configurations are used by OutputFormat return getInstance(job.getConfiguration()); } /** * * @param conf * @return * * @deprecated since 1.4, use {@link #setBlockSize(Configuration, int)} no other configurations are used by OutputFormat */ protected static Instance getInstance(Configuration conf) {
Do not forget to remove this deprecated code someday.
import org.apache.accumulo.trace.instrument.Span; import org.apache.accumulo.trace.instrument.Trace;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
if (ret > 0) return 1; if (ret < 0) return -1; if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (blockIndex != other.blockIndex) return false; if (recordIndex != other.recordIndex) return false; if (blkIndex < 0) return end; if (blockIndex == -1) return end; if (blockIndex == -1) return null; if (klen >= 0) return; if (this == other) return true; if (!(other instanceof Entry)) return false; if (cmp > 0) return false; if (cmp == 0 && !greater) return true;
Remove this call to "exit" or ensure it is really required.
if (iteratorName == null || key == null || value == null) this.key = URLDecoder.decode(tokenizer.nextToken(), "UTF-8"); return new String(iteratorName + FIELD_SEP + URLEncoder.encode(key, "UTF-8") + FIELD_SEP + URLEncoder.encode(value, "UTF-8"));
Define and throw a dedicated exception instead of using a generic one.
if (bytes > 0 && Integer.parseInt(setting) > 10) { log.warn("System swappiness setting is greater than ten (" + setting + ") which can cause time-sensitive operations to be delayed. "
Refactor this code to not nest more than 3 if/for/while/switch/try statements.
import org.apache.accumulo.fate.Repo;
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.
ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(mi, is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), new DefaultIteratorEnvironment()); ai.init(new SortedMapIterator(tm1), is.getOptions(), new DefaultIteratorEnvironment()); ai.init(new SortedMapIterator(tm1), is.getOptions(), new DefaultIteratorEnvironment()); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null); ai.init(new SortedMapIterator(tm1), is.getOptions(), null);
Immediately return this expression instead of assigning it to the temporary variable "bos2".
import org.apache.accumulo.core.security.tokens.InstanceTokenWrapper; InstanceTokenWrapper auths = SecurityConstants.getSystemCredentials(); conn = HdfsZooInstance.getInstance().getConnector(auths); InstanceTokenWrapper creds = SecurityConstants.getSystemCredentials(); InstanceTokenWrapper creds = SecurityConstants.getSystemCredentials();
Immediately return this expression instead of assigning it to the temporary variable "ret".
package org.apache.accumulo.test.randomwalk.concurrent; 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.
@Test(timeout = 4 * 60 * 1000)
Either log or rethrow this exception.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
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.
import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import org.apache.accumulo.server.util.NamingThreadFactory; import org.apache.accumulo.server.zookeeper.DistributedWorkQueue; private DistributedWorkQueue bulkFailedCopyQ; ThreadPoolExecutor distWorkQThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool( ServerConfiguration.getSystemConfiguration().getCount(Property.TSERV_WORKQ_THREADS), new NamingThreadFactory("distributed work queue")); bulkFailedCopyQ = new DistributedWorkQueue(Constants.ZROOT + "/" + HdfsZooInstance.getInstance().getInstanceID() + Constants.ZBULK_FAILED_COPYQ); try { bulkFailedCopyQ.startProcessing(new BulkFailedCopyProcessor(), distWorkQThreadPool); } catch (Exception e1) { throw new RuntimeException("Failed to start distributed work queue for copying ", e1); }
Move this variable to comply with Java Code Conventions.
import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.client.ScannerBase; import org.apache.accumulo.core.security.thrift.AuthInfo; public MetaDataTableScanner(Instance instance, AuthInfo auths, Range range, CurrentState state) { Connector connector = instance.getConnector(auths); configureScanner(mdScanner, state); static public void configureScanner(ScannerBase scanner, CurrentState state) { ColumnFQ.fetch(scanner, Constants.METADATA_PREV_ROW_COLUMN); scanner.fetchColumnFamily(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY); scanner.fetchColumnFamily(Constants.METADATA_FUTURE_LOCATION_COLUMN_FAMILY); scanner.fetchColumnFamily(Constants.METADATA_LOG_COLUMN_FAMILY); scanner.fetchColumnFamily(Constants.METADATA_CHOPPED_COLUMN_FAMILY); scanner.addScanIterator(new IteratorSetting(1000, "wholeRows", WholeRowIterator.class)); IteratorSetting tabletChange = new IteratorSetting(1001, "tabletChange", TabletStateChangeIterator.class); if (state != null) { TabletStateChangeIterator.setCurrentServers(tabletChange, state.onlineTabletServers()); TabletStateChangeIterator.setOnlineTables(tabletChange, state.onlineTables()); TabletStateChangeIterator.setMerges(tabletChange, state.merges()); } scanner.addScanIterator(tabletChange); } public MetaDataTableScanner(Instance instance, AuthInfo auths, Range range) { this(instance, auths, range, null); public static TabletLocationState createTabletLocationState(Key k, Value v) throws IOException { final SortedMap<Key,Value> decodedRow = WholeRowIterator.decodeRow(k, v); Entry<Key,Value> e = iter.next(); return createTabletLocationState(e.getKey(), e.getValue());
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.util.TreeMap; private static String principal = "root"; @SuppressWarnings("serial") private static Map<String, String> properties = new TreeMap<String, String>() {{ put("password",secret);}}; creds = client.login(principal, properties); assertTrue(client.authenticateUser(creds, "root", s2pp(secret))); assertFalse(client.authenticateUser(creds, "root", s2pp(""))); client.createLocalUser(creds, "stooge", s2bb("password")); Set<String> users = client.listLocalUsers(creds); client.changeLocalUserPassword(creds, "stooge", s2bb("")); assertTrue(client.authenticateUser(creds, "stooge", s2pp(""))); @SuppressWarnings("serial") ByteBuffer stooge = client.login("stooge", new TreeMap<String,String>() {{put("password",""); }}); client.dropLocalUser(creds, "stooge"); users = client.listLocalUsers(creds); private Map<String, String> s2pp(String cf) { Map<String, String> toRet = new TreeMap<String, String>(); toRet.put("password", cf); return toRet; }
Remove this hard-coded password.
* Using this class these resources may be shared among multiple tables. * Returns a BatchWriter for a particular table. * * Returns true if this batch writer has been closed. *
Complete the task associated to this TODO comment.
package org.apache.accumulo.test.functional;
Move the "org.apache.accumulo.test.randomwalk.unit.CreateTable" string literal on the left side of this string comparison.
/** * Inserts 10K rows (50K entries) into accumulo with each row having 5 entries. */
Replace this use of System.out or System.err by a logger.
return ("generates a list of commands previously executed"); clearHist = new Option("c", "clear", false, "clear history file"); }
Replace all tab characters in this file by sequences of white-spaces.
import org.apache.accumulo.core.metadata.MetadataTable; @Test(timeout = 60 * 1000) static Map<String,String> map(Iterable<Entry<String,String>> i) { Map<String,String> result = new HashMap<String,String>(); for (Entry<String,String> e : i) { TableExistsException, AccumuloSecurityException, TableNotFoundException { AccumuloSecurityException, TableNotFoundException, TableExistsException { AccumuloSecurityException { AccumuloSecurityException { verifyHasOnlyTheseTablePermissions(c, c.whoami(), MetadataTable.NAME, TablePermission.READ, TablePermission.ALTER_TABLE); private void createTestTable(Connector c) throws Exception, MutationsRejectedException { throw new AccumuloSecurityException(test_user_conn.whoami(), org.apache.accumulo.core.client.impl.thrift.SecurityErrorCode.PERMISSION_DENIED, e1); TableExistsException, AccumuloSecurityException, TableNotFoundException, MutationsRejectedException { AccumuloSecurityException { AccumuloSecurityException {
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
package org.apache.accumulo.server.master.balancer; import java.util.Set; public interface LoggerUser extends Comparable<LoggerUser> { Set<String> getLoggers(); }
Return empty string instead.
RegExFilter result = new RegExFilter(); result.setSource(getSource().deepCopy(env));
Remove the literal "true" boolean value.
AccumuloInputFormat.setConnectorInfo(job, user, new PasswordToken(pass));
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
public static final List<String> main() throws IOException { List<String> result = new ArrayList<String>(); InputStream input = BasicServlet.class.getClassLoader().getResourceAsStream("slaves"); byte[] buffer = new byte[1024]; int n; StringBuilder all = new StringBuilder(); while ((n = input.read(buffer)) > 0) all.append(new String(buffer, 0, n)); for (String slave : all.toString().split("\n")) { slave = slave.trim(); if (slave.length() > 0 && slave.indexOf("#") < 0) result.add(slave); return result; }
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. */ private TabletServerStatus status; private TServerInstance instance; public TServerUsesLoggers(TServerInstance instance, TabletServerStatus status) { this.instance = instance; this.status = status; } @Override public Set<String> getLoggers() { return Collections.unmodifiableSet(status.loggers); } @Override public int compareTo(LoggerUser o) { if (o instanceof TServerUsesLoggers) return instance.compareTo(((TServerUsesLoggers) o).instance); return -1; } @Override public int hashCode() { return instance.hashCode(); } public TServerInstance getInstance() { return instance; }
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
MasterMonitorInfo stats = client.getMasterStats(Tracer.traceInfo(), SecurityConstants.getSystemCredentials());
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
package org.apache.accumulo.trace.instrument; import org.apache.accumulo.trace.thrift.TInfo;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
@Test(timeout=30*1000)
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.client.security.tokens.PasswordToken; Connector conn = mi.getConnector("root", new PasswordToken(""));
Rename "connector" which hides the field declared at line 67.
if (args.length != 4) throw new IllegalArgumentException("Expected arguments: <instance name> <zookeeper server> <username> <password>");
Remove this call to "exit" or ensure it is really required.
import org.apache.accumulo.core.client.security.SecurityErrorCode; if (ae.getSecurityErrorCode().equals(SecurityErrorCode.PERMISSION_DENIED)) {
Do not forget to remove this deprecated code someday.
package org.apache.accumulo.examples.wikisearch.iterator; import org.apache.accumulo.examples.wikisearch.parser.EventFields; import org.apache.accumulo.examples.wikisearch.parser.QueryEvaluator;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import org.apache.accumulo.core.security.thrift.Credential; public void initializeSecurity(Credential itw, String rootuser) throws AccumuloSecurityException {
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
import java.nio.charset.Charset; private Charset utf8 = Charset.forName("UTF8"); List<IteratorSetting> iters = IteratorUtil.decodeIteratorSettings(hex.decode(tokens[i].split("=")[1].getBytes(utf8)));
Move this variable to comply with Java Code Conventions.
import org.apache.accumulo.trace.thrift.RemoteSpan;
Remove the redundant '!unknownSymbol!' thrown exception declaration(s).
import java.nio.charset.Charset; private static final Charset utf8 = Charset.forName("UTF8"); out.write(("could not get resource " + path + "").getBytes(utf8));
Move this variable to comply with Java Code Conventions.
Connector conn = new ZooKeeperInstance(accumulo.getConfig().getInstanceName(), accumulo.getConfig().getZooKeepers()).getConnector("root", new PasswordToken("superSecret")); Connector uconn = new ZooKeeperInstance(accumulo.getConfig().getInstanceName(), accumulo.getConfig().getZooKeepers()).getConnector("user1", new PasswordToken("pass1")); Connector conn = new ZooKeeperInstance(accumulo.getConfig().getInstanceName(), accumulo.getConfig().getZooKeepers()).getConnector("root", new PasswordToken("superSecret"));
Either log or rethrow this exception.
import org.apache.accumulo.core.util.RootTable; String zRootLocPath = ZooUtil.getRoot(this) + RootTable.ZROOT_TABLET_LOCATION;
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. */ @SuppressWarnings("all") public class Column implements org.apache.thrift.TBase<Column, Column._Fields>, java.io.Serializable, Cloneable { @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]*$'.
package org.apache.accumulo.test.randomwalk.concurrent; 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.
package org.apache.accumulo.examples.wikisearch.iterator; import org.apache.accumulo.examples.wikisearch.parser.JexlOperatorConstants;
Rename this local variable to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
* A lexicoder for an unsigned integer. It sorts 0 before -1 and does not preserve the native sort order of a Java integer because Java does not contain an * unsigned integer. If Java had an unsigned integer type, this would correspond to its sort order.
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. */
Replace all tab characters in this file by sequences of white-spaces.
if (children == null || children.size() == 0) {
Use isEmpty() to check whether the collection is empty or not.
import org.apache.accumulo.core.cli.Help; import com.beust.jcommander.Parameter; static class Opts extends Help { @Parameter(names="--output", description="the destiation directory") String outputDirectory; @Parameter(names="--numThreads", description="number of threads to use when generating files") int numThreads = 4; @Parameter(names="--start", description="the start number for test data") long start = 0; @Parameter(names="--end", description="the maximum number for test data") long end = 10*1000*1000; @Parameter(names="--splits", description="the number of splits in the data") long numsplits = 4; } Opts opts = new Opts(); opts.parseArgs(CreateRFiles.class.getName(), args); long splitSize = Math.round((opts.end - opts.start) / (double) opts.numsplits); long currStart = opts.start; long currEnd = opts.start + splitSize; ExecutorService threadPool = Executors.newFixedThreadPool(opts.numThreads); while (currEnd <= opts.end && currStart < currEnd) { final String tia = String.format("--rfile /%s/mf%05d --timestamp 1 --size 50 --random 56 --rows %d --start %d --user root", opts.outputDirectory, count, currEnd - currStart, currStart); currEnd = Math.min(opts.end, currStart + splitSize);
Remove this call to "exit" or ensure it is really required.
package org.apache.accumulo.test.performance.metadata;
Move the "org.apache.accumulo.test.randomwalk.unit.CreateTable" string literal on the left side of this string comparison.
/** * An abstract input format to provide shared methods common to all other input format classes. At the very least, any classes inheriting from this class will * need to define their own {@link RecordReader}. */ return InputConfigurator.getBatchScanConfig(CLASS, getConfiguration(context), tableName); * @since 1.6.0
Do not forget to remove this deprecated code someday.
import org.apache.accumulo.core.file.rfile.RFile; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; mapFiles.put(tdir + "/" + RFile.EXTENSION + "_000_000", new DataFileValue(1000017 + i, 10000 + i));
Either log or rethrow this exception.
if (version == RFile.RINDEX_VER_6 || version == RFile.RINDEX_VER_7) { if (version == RFile.RINDEX_VER_6 || version == RFile.RINDEX_VER_7) {
Remove this unused private "appendProp" method.