auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void activateDeviceRequest(final String organisationIdentification, @Identification final String deviceIdentification) throws FunctionalException { LOGGER.debug("Activating device on behalf of organisation [{}]", deviceIdentification, organisationIdentification); final Organisation organisation = this.findOrganisation(organisationIdentification); <START> this.isAllowed(organisation, PlatformFunction.DEACTIVATE_DEVICE); <END> if (this.deviceRepository.findByDeviceIdentification(deviceIdentification) == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_ADMIN); } this.enqueueActivateDeviceRequest(organisationIdentification, deviceIdentification); }</code><technical_language>this check if ACTIVATE_DEVICE is allowed (instead of DEACTIVATE_DEVICE)</technical_language>

Target:
public void activateDeviceRequest(final String organisationIdentification, @Identification final String deviceIdentification) throws FunctionalException { LOGGER.debug("Activating device on behalf of organisation [{}]", deviceIdentification, organisationIdentification); final Organisation organisation = this.findOrganisation(organisationIdentification); this.isAllowed(organisation, PlatformFunction.ACTIVATE_DEVICE); if (this.deviceRepository.findByDeviceIdentification(deviceIdentification) == null) { throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_ADMIN); } this.enqueueActivateDeviceRequest(organisationIdentification, deviceIdentification); }
Source:
<code>public void close() { for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) { try { i.next().run(); } catch (Throwable err) { <START> log.error("Failed to execute per-request cleanup", err); <END> } i.remove(); } }</code><technical_language>This a per-request cleanup, a cleanup for a PrologEnvironment. reuse log message copied other location, lead a problem identify wrong area of code is involved</technical_language>

Target:
public void close() { for (final Iterator<Runnable> i = cleanup.iterator(); i.hasNext();) { try { i.next().run(); } catch (Throwable err) { log.error("Failed to execute cleanup for PrologEnvironment", err); } i.remove(); } }
Source:
<code>@Override public double getHitRate(){ <START> return (getHitCount()*1.0)/getRequestCount(); <END> }</code><technical_language>divide zero possible, safeguarded</technical_language>

Target:
@Override public double getHitRate(){ return getRequestCount()>0?((getHitCount()*1.0)/getRequestCount()):0; }
Source:
<code>private Set<String> indicesFromElastic() throws IOException { final String endpoint = "/_alias"; final Response response = client.performRequest(new Request("GET", endpoint)); try (InputStream is = response.getEntity().getContent()) { final JsonNode root = mapper.readTree(is); <START> if (!root.isObject() || root.size() == 0) { <END> final String message = String.format(Locale.ROOT, "Invalid response for %s/%s " + "Expected object of at least size 1 got %s (of size %d)", response.getHost(), response.getRequestLine(), root.getNodeType(), root.size()); throw new IllegalStateException(message); } Set<String> indices = Sets.newHashSet(root.fieldNames()); return indices; } }</code><technical_language>Pls conjunction format: java if (!(root.isObject() && root.size() > 0)) { // .... }</technical_language>

Target:
private Set<String> indicesFromElastic() throws IOException { final String endpoint = "/_alias"; final Response response = client.performRequest(new Request("GET", endpoint)); try (InputStream is = response.getEntity().getContent()) { final JsonNode root = mapper.readTree(is); if (!(root.isObject() && root.size() > 0)) { final String message = String.format(Locale.ROOT, "Invalid response for %s/%s " + "Expected object of at least size 1 got %s (of size %d)", response.getHost(), response.getRequestLine(), root.getNodeType(), root.size()); throw new IllegalStateException(message); } Set<String> indices = Sets.newHashSet(root.fieldNames()); return indices; } }
Source:
<code>public boolean onCommand(CommandPerformEvent event) { if (event.getArgs().length == 0) { return false; } else { try { HttpResponse<JsonNode> jsonResponse = Unirest.get("<LINK_0>") .field("a", "get_info") .header("accept", "application/json") .asJson(); <START> double dogeyer = jsonResponse.getBody().getObject().getJSONObject("data").getJSONObject("info").getDouble("doge_usd"); <END> double amtInUSDtoDoge = Double.parseDouble(event.getArgs()[0]); amtInUSDtoDoge = amtInUSDtoDoge / dogeyer; double amtInDogetoUSD = Double.parseDouble(event.getArgs()[0]); amtInDogetoUSD = amtInDogetoUSD * dogeyer; amtInDogetoUSD = (double) Math.round(amtInDogetoUSD * 100) / 100; amtInUSDtoDoge = (double) Math.round(amtInUSDtoDoge * 100) / 100; event.respond(Colors.BOLD + "USD --> Doge: " + Colors.NORMAL + Colors.UNDERLINE + amtInUSDtoDoge); event.respond(Colors.BOLD + "Doge --> USD: " + Colors.NORMAL + Colors.UNDERLINE + amtInDogetoUSD); } catch (UnirestException e) { e.printStackTrace(); } return true; } }</code><technical_language>extraneous spacing this line. Also, please rename variable :P</technical_language>

Target:
public boolean onCommand(CommandPerformEvent event) { if (event.getArgs().length == 0) { return false; } else { try { HttpResponse<JsonNode> jsonResponse = Unirest.get("<LINK_0>") .field("a", "get_info") .header("accept", "application/json") .asJson(); double amtFromDogeApi = jsonResponse.getBody().getObject().getJSONObject("data").getJSONObject("info").getDouble("doge_usd"); double amtInUSDtoDoge = Double.parseDouble(event.getArgs()[0]); amtInUSDtoDoge = amtInUSDtoDoge / amtFromDogeApi; double amtInDogetoUSD = Double.parseDouble(event.getArgs()[0]); amtInDogetoUSD = amtInDogetoUSD * amtFromDogeApi; amtInDogetoUSD = (double) Math.round(amtInDogetoUSD * 100) / 100; amtInUSDtoDoge = (double) Math.round(amtInUSDtoDoge * 100) / 100; event.respond(Colors.BOLD + "USD --> Doge: " + Colors.NORMAL + Colors.UNDERLINE + amtInUSDtoDoge); event.respond(Colors.BOLD + "Doge --> USD: " + Colors.NORMAL + Colors.UNDERLINE + amtInDogetoUSD); } catch (UnirestException e) { throw new DogeCoinException("An error occurred in the conversion process", e); } return true; } }
Source:
<code>public static int getSegmentForKey(Object key, Cache cache) { KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); if (keyPartitioner != null) { return keyPartitioner.getSegment(key); } <START> return SegmentSpecificCommand.UNKNOWN_SEGMENT; <END> }</code><technical_language>throw exception</technical_language>

Target:
public static int getSegmentForKey(Object key, Cache cache) { KeyPartitioner keyPartitioner = extractComponent(cache, KeyPartitioner.class); return keyPartitioner.getSegment(key); }
Source:
<code>public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); <START> } catch (InstantiationException ex) { <END> java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TestNews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } TestNews test = new TestNews(); test.setVisible(true); try { userDirectory = new ClassPathResource("NewsData").getFile().toString() + "\\"; WORD_VECTORS_PATH = userDirectory + "NewsWordVector.txt"; tokenizerFactory = new DefaultTokenizerFactory(); tokenizerFactory.setTokenPreProcessor(new CommonPreprocessor()); net = ModelSerializer.restoreMultiLayerNetwork(userDirectory + "NewsModel.net"); wordVectors = WordVectorSerializer.loadTxtVectors(new File(WORD_VECTORS_PATH)); } catch (Exception e) { } }</code><technical_language>slf4j JUL</technical_language>

Target:
public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { Logger.getLogger(TestNews.class.getName()).log(Level.SEVERE, null, ex); } TestNews test = new TestNews(); test.setVisible(true); try { userDirectory = new ClassPathResource("NewsData").getFile().getAbsolutePath() + File.separator; WORD_VECTORS_PATH = userDirectory + "NewsWordVector.txt"; tokenizerFactory = new DefaultTokenizerFactory(); tokenizerFactory.setTokenPreProcessor(new CommonPreprocessor()); net = ModelSerializer.restoreMultiLayerNetwork(userDirectory + "NewsModel.net"); wordVectors = WordVectorSerializer.loadTxtVectors(new File(WORD_VECTORS_PATH)); } catch (Exception e) { } }
Source:
<code>public void onCreate() { super.onCreate(); initExceptionHandling(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); bus = new Bus(); ViewAnimations.init(getResources()); currentTheme = unmarshalCurrentTheme(); appLanguageState = new AppLanguageState(this); funnelManager = new FunnelManager(this); sessionFunnel = new SessionFunnel(this); editTokenStorage = new EditTokenStorage(this); cookieManager = new SharedPreferenceCookieManager(); database = new Database(this); enableWebViewDebugging(); OkHttpConnectionFactory okHttpConnectionFactory = new OkHttpConnectionFactory(this); Api.setConnectionFactory(okHttpConnectionFactory); Set<RequestListener> requestListeners = new HashSet<>(); <START> requestListeners.add(new RequestLoggingListener()); <END> ImagePipelineConfig config = OkHttpImagePipelineConfigFactory .newBuilder(this, okHttpConnectionFactory.client()) .setRequestListeners(requestListeners) .build(); Fresco.initialize(this, config); zeroHandler = new WikipediaZeroHandler(this); pageCache = new PageCache(this); AccountUtil.createAccountForLoggedInUser(); UserOptionContentResolver.registerAppSyncObserver(this); registerReadingListPageObserver(); }</code><technical_language>curious this is desirable HttpLoggingInterceptor set in OkHttpConnectionFactory</technical_language>

Target:
public void onCreate() { super.onCreate(); initExceptionHandling(); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); bus = new Bus(); ViewAnimations.init(getResources()); currentTheme = unmarshalCurrentTheme(); appLanguageState = new AppLanguageState(this); funnelManager = new FunnelManager(this); sessionFunnel = new SessionFunnel(this); editTokenStorage = new EditTokenStorage(this); cookieManager = new SharedPreferenceCookieManager(); database = new Database(this); enableWebViewDebugging(); OkHttpConnectionFactory okHttpConnectionFactory = new OkHttpConnectionFactory(this); Api.setConnectionFactory(okHttpConnectionFactory); ImagePipelineConfig config = OkHttpImagePipelineConfigFactory .newBuilder(this, okHttpConnectionFactory.client()) .build(); Fresco.initialize(this, config); zeroHandler = new WikipediaZeroHandler(this); pageCache = new PageCache(this); AccountUtil.createAccountForLoggedInUser(); UserOptionContentResolver.registerAppSyncObserver(this); registerReadingListPageObserver(); }
Source:
<code>void writeMasterPasswordInfo(Resource file,String message,char[] masterPasswordArray) throws IOException { <START> BufferedWriter w = new BufferedWriter(new OutputStreamWriter(file.out())); <END> DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); w.write("This file was created at "+dateFormat.format(new Date())); w.newLine(); w.newLine(); w.write(message); if (masterPasswordArray!=null) w.write(masterPasswordArray); w.newLine(); w.newLine(); w.write("Test the master password by logging in as user \"root\""); w.newLine(); w.newLine(); w.write("This file should be removed after reading !!!."); w.newLine(); w.close(); }</code><technical_language>This method need try-with-resources spaces operators</technical_language>

Target:
void writeMasterPasswordInfo(Resource file, String message, char[] masterPasswordArray) throws IOException { try (BufferedWriter w = new BufferedWriter(new OutputStreamWriter(file.out()))) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); w.write("This file was created at " + dateFormat.format(new Date())); w.newLine(); w.newLine(); w.write(message); if (masterPasswordArray != null) { w.write(masterPasswordArray); } w.newLine(); w.newLine(); w.write("Test the master password by logging in as user \"root\""); w.newLine(); w.newLine(); w.write("This file should be removed after reading !!!."); w.newLine(); } }
Source:
<code>public static Sso map(SsoMethod entity, Sso template) { Sso model = (template == null) ? new Sso() : template; model.setMethods(new Methods()); if (entity == SsoMethod.GUEST_AGENT) { model.getMethods().getMethods().add(org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT.toString()); } else if (entity == SsoMethod.NONE) { <START> model.getMethods().getMethods().add(org.ovirt.engine.api.model.SsoMethod.NONE.toString()); <END> } return model; }</code><technical_language>I mapping of backend result in empty list of methods, this: <sso> <methods/> </sso> explicitly SSO method is enabled</technical_language>

Target:
public static Sso map(SsoMethod entity, Sso template) { Sso model = (template == null) ? new Sso() : template; model.setMethods(new Methods()); if (entity == SsoMethod.GUEST_AGENT) { model.getMethods().getMethods().add(org.ovirt.engine.api.model.SsoMethod.GUEST_AGENT.toString()); } return model; }
Source:
<code>public void testCreateUpdateAndDeleteFloatingIP() { for (String region : api.getConfiguredRegions()) { FloatingIPApi floatingIPApi = api.getFloatingIPApi(region); NetworkApi networkApi = api.getNetworkApi(region); FloatingIP floatingIPGet = null; Network network; try { network = networkApi.list().concat().firstMatch(new Predicate<Network>() { <START> @Override <END> public boolean apply(@Nullable Network input) { return input.getExternal(); } }).orNull(); if (network == null) Assert.fail("Cannot find a suitable external network. Please add it manually or contact your administrator"); FloatingIP floatingIP = floatingIPApi.create(FloatingIP.createBuilder(network.getId()).availabilityZone(network.getAvailabilityZone()).build()); Set<FloatingIP> floatingIPs = floatingIPApi.list().concat().toSet(); floatingIPGet = floatingIPApi.get(floatingIP.getId()); assertNotNull(floatingIPGet); assertTrue(floatingIPs.contains(floatingIP)); } finally { assertTrue(floatingIPApi.delete(floatingIPGet.getId())); } } }</code><technical_language>If input is nullable guard a NPE</technical_language>

Target:
public void testCreateUpdateAndDeleteFloatingIP() { for (String region : api.getConfiguredRegions()) { FloatingIPApi floatingIPApi = api.getFloatingIPApi(region); NetworkApi networkApi = api.getNetworkApi(region); FloatingIP floatingIPGet = null; Network network; try { network = networkApi.list().concat().firstMatch(new Predicate<Network>() { @Override public boolean apply(Network input) { return input.getExternal(); } }).orNull(); if (network == null) Assert.fail("Cannot find a suitable external network. Please add it manually or contact your administrator"); FloatingIP floatingIP = floatingIPApi.create(FloatingIP.createBuilder(network.getId()).availabilityZone(network.getAvailabilityZone()).build()); Set<FloatingIP> floatingIPs = floatingIPApi.list().concat().toSet(); floatingIPGet = floatingIPApi.get(floatingIP.getId()); assertNotNull(floatingIPGet); assertTrue(floatingIPs.contains(floatingIP)); } finally { assertTrue(floatingIPApi.delete(floatingIPGet.getId())); } } }
Source:
<code>public RedisResponse executeCommandWithResponse(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); byte[] byteField = commandElems.get(FIELD_INDEX); ByteArrayWrapper field = new ByteArrayWrapper(byteField); ByteArrayWrapper key = command.getKey(); RedisHash map = getRedisHash(context, key); boolean hasField = map.containsKey(field); <START> return RedisResponse.integer(hasField ? EXISTS : NOT_EXISTS); <END> }</code><technical_language>do of supporting a flavor of "integer(boolean)" respond 1 if true 0 if false? a large number of redis commands do this</technical_language>

Target:
public RedisResponse executeCommandWithResponse(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); byte[] byteField = commandElems.get(FIELD_INDEX); ByteArrayWrapper field = new ByteArrayWrapper(byteField); ByteArrayWrapper key = command.getKey(); RedisHashCommands redisHashCommands = createRedisHashCommands(context); return RedisResponse.integer(redisHashCommands.hexists(key, field)); }
Source:
<code>public void onResponse(Map<String, Object> response) { try { continueRefreshCapabilities(new AtomicBoolean(), vds, <START> oldVDS, <END> (VDSReturnValue) response.get("result")); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }</code><technical_language>clone here? In this field instead of two</technical_language>

Target:
public void onResponse(Map<String, Object> response) { try { processRefreshCapabilitiesResponse(new AtomicBoolean(), vds, vds.clone(), (VDSReturnValue) response.get("result")); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }
Source:
<code>private void writeServerEnvProperties(File file, Map<String, String> mavenProperties) throws IOException { makeParentDirectory(file); PrintWriter writer = null; try { writer = new PrintWriter(file, "UTF-8"); writer.println(HEADER); for (Map.Entry<String, String> entry : mavenProperties.entrySet()) { String key = entry.getKey(); writer.print(key); writer.print("="); String value = entry.getValue(); <START> writer.println((value != null) ? value.replace("\\", "/") : ""); <END> if (value == null) { log.error("The value of the server.env property " + entry.getKey() + " is null. Verify if the needed POM properties are set correctly."); } } } finally { if (writer != null) { writer.close(); } } }</code><technical_language>a replace need done here</technical_language>

Target:
private void writeServerEnvProperties(File file, Map<String, String> mavenProperties) throws IOException { makeParentDirectory(file); PrintWriter writer = null; try { writer = new PrintWriter(file, "UTF-8"); writer.println(HEADER); for (Map.Entry<String, String> entry : mavenProperties.entrySet()) { String key = entry.getKey(); writer.print(key); writer.print("="); String value = entry.getValue(); writer.println((value != null) ? value.replace("\\", "/") : ""); if (value == null) { log.warn("The value of the server.env property " + entry.getKey() + " is null. Verify if the needed POM properties are set correctly."); } } } finally { if (writer != null) { writer.close(); } } }
Source:
<code>private Collection<ClusterNode> nodes() throws IgniteCheckedException { CacheMode cacheMode = cctx.config().getCacheMode(); Integer part = partition(); switch (cacheMode) { case LOCAL: if (prj != null) U.warn(log, "Ignoring query projection because it's executed over LOCAL cache " + "(only local node will be queried): " + this); if (type == SCAN && cctx.config().getCacheMode() == LOCAL && part != null && part >= cctx.affinity().partitions()) throw new IgniteCheckedException("Invalid partition number: " + part); return Collections.singletonList(cctx.localNode()); case REPLICATED: if (prj != null || part != null) return nodes(cctx, prj, part); if (cctx.affinityNode() && !cctx.topology().localPartitionMap().hasMovingPartitions()) return Collections.singletonList(cctx.localNode()); Collection<ClusterNode> affNodes = nodes(cctx, null, null); List<ClusterNode> nodes = new ArrayList<>(affNodes); Collections.shuffle(nodes); for (ClusterNode node : nodes) { <START> if (!cctx.topology().partitions(node.id()).hasMovingPartitions()) { <END> return Collections.singletonList(node); } } return affNodes; case PARTITIONED: return nodes(cctx, prj, part); default: throw new IllegalStateException("Unknown cache distribution mode: " + cacheMode); } }</code><technical_language>I worry a case is node OWNING partitions (i.e. some partitions lost). In a case affinity nodes for a query execution. duplicates possible. I suggest resort (single) affinity node in case. previous behavior same</technical_language>

Target:
private Collection<ClusterNode> nodes() throws IgniteCheckedException { CacheMode cacheMode = cctx.config().getCacheMode(); Integer part = partition(); switch (cacheMode) { case LOCAL: if (prj != null) U.warn(log, "Ignoring query projection because it's executed over LOCAL cache " + "(only local node will be queried): " + this); if (type == SCAN && cctx.config().getCacheMode() == LOCAL && part != null && part >= cctx.affinity().partitions()) throw new IgniteCheckedException("Invalid partition number: " + part); return Collections.singletonList(cctx.localNode()); case REPLICATED: if (prj != null || part != null) return nodes(cctx, prj, part); GridDhtPartitionTopology topology = cctx.topology(); if (cctx.affinityNode() && !topology.localPartitionMap().hasMovingPartitions()) return Collections.singletonList(cctx.localNode()); topology.readLock(); try { Collection<ClusterNode> affNodes = nodes(cctx, null, null); List<ClusterNode> nodes = new ArrayList<>(affNodes); Collections.shuffle(nodes); for (ClusterNode node : nodes) { if (!topology.partitions(node.id()).hasMovingPartitions()) return Collections.singletonList(node); } return affNodes; } finally { topology.readUnlock(); } case PARTITIONED: return nodes(cctx, prj, part); default: throw new IllegalStateException("Unknown cache distribution mode: " + cacheMode); } }
Source:
<code>public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); <START> if (previous.getPreparedId().getResultMetadataId().equals(stmt.getPreparedId().metadata)) { <END> return previous; } else { preparedQueries.put(stmt.getPreparedId().id, stmt); return stmt; } } return stmt; }</code><technical_language>This if (previous.getPreparedId().getResultMetadataId().equals(stmt.getPreparedId().getResultMetadataId()))</technical_language>

Target:
public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().boundValuesMetadata.id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); previous.getPreparedId().resultSetMetadata = stmt.getPreparedId().resultSetMetadata; return previous; } return stmt; }
Source:
<code>private List<LogsForNamespaceAndUseCase> fetchHistoryFromRemote(List<HistoryQuery> historyQueries, TimeLockPaxosHistoryProvider remote) { try { return remote.getPaxosHistory(AUTH_HEADER, historyQueries); } catch (Exception e) { log.warn("The remote failed to provide the history," <START> + "we cannot perform corruption checks without history from all nodes."); <END> throw new RuntimeException(e.getCause()); } }</code><technical_language>nit: Please include e</technical_language>

Target:
private PaxosHistoryOnRemote fetchHistoryFromRemote(List<HistoryQuery> historyQueries, TimeLockPaxosHistoryProvider remote) { try { return remote.getPaxosHistory(AUTH_HEADER, historyQueries); } catch (Exception exception) { log.warn("The remote failed to provide the history," + "we cannot perform corruption checks without history from all nodes.", exception); throw exception; } }
Source:
<code>public BranchMergeOperation exclude(String ... ids) { <START> return exclude(Arrays.copyOf(ids, ids.length)); <END> }</code><technical_language>ImmutableSet.copyOf(E[] elements)</technical_language>

Target:
public BranchMergeOperation exclude(String ... ids) { return exclude(ImmutableSet.copyOf(ids)); }
Source:
<code>public final ClientBuilder readTimeout(long readTimeout, TimeUnit unit) { if (thisReadTimeout.isPresent()) { <START> Preconditions.checkArgument(!thisReadTimeout.isPresent(), "readTimeout already set"); <END> } thisReadTimeout = Optional.of(Duration.millis(TimeUnit.MILLISECONDS.convert(readTimeout, unit))); return this; }</code><technical_language>true</technical_language>

Target:
public final ClientBuilder readTimeout(long readTimeout, TimeUnit unit) { Preconditions.checkArgument(!thisReadTimeout.isPresent(), "readTimeout already set"); thisReadTimeout = Optional.of(Duration.millis(TimeUnit.MILLISECONDS.convert(readTimeout, unit))); return this; }
Source:
<code>protected void formatColumnValue(StringBuilder builder, String schemaName, Map<String, String> schemaParameters, Schema.Type type, Object value) { if (schemaName != null) { super.formatColumnValue(builder, schemaName, schemaParameters, type, value); <START> } <END> if (Schema.Type.BOOLEAN.equals(type)) { builder.append((Boolean) value ? "TRUE" : "FALSE"); return; } super.formatColumnValue(builder, schemaName, schemaParameters, type, value); }</code><technical_language>Is return; missing here? I for default: clause in super method's switch schemaName. if expect hit of cases hit buggie case BOOLEAN base formatColumnValue. sense default: is missing? If I a return; is missing here</technical_language>

Target:
protected void formatColumnValue(StringBuilder builder, String schemaName, Map<String, String> schemaParameters, Schema.Type type, Object value) { if (schemaName != null && super.formatLogicalColumnValue(builder, schemaName, value)) { return; } if (Schema.Type.BOOLEAN.equals(type)) { builder.append((Boolean) value ? "TRUE" : "FALSE"); return; } super.formatColumnValue(builder, schemaName, schemaParameters, type, value); }
Source:
<code>public void testAsyncConnectionWithReconnect() throws IOException, InterruptedException { TestHandler handler = new TestHandler(); Connection nc = null; int port = NatsTestServer.nextPort(); Options options = new Options.Builder(). server("nats://localhost:"+port). maxReconnects(-1). reconnectWait(Duration.ofMillis(100)). connectionListener(handler). build(); try { Nats.connectAsynchronously(options, true); <START> sleep(5000); END> nc = handler.getConnection(); assertNotNull(nc); handler.prepForStatusChange(Events.RECONNECTED); try (NatsTestServer ts = new NatsTestServer(port, false)) { allowTimeToConnectAssertOpen(nc, handler); } } finally { closeConnectionAssertClosed(nc); } }</code><technical_language>a bit more deterministic options.getConnectionTimeout() + 100 in case default timeout changes</technical_language>

Target:
public void testAsyncConnectionWithReconnect() throws IOException, InterruptedException { TestHandler handler = new TestHandler(); Connection nc = null; int port = NatsTestServer.nextPort(); Options options = new Options.Builder(). server("nats://localhost:"+port). maxReconnects(-1). reconnectWait(Duration.ofMillis(100)). connectionListener(handler). build(); try { Nats.connectAsynchronously(options, true); sleep(5000); nc = handler.getConnection(); assertNotNull(nc); handler.prepForStatusChange(Events.RECONNECTED); try (NatsTestServer ts = new NatsTestServer(port, false)) { waitThenAssertConnected(nc, handler); } } finally { closeThenAssertClosed(nc); } }
Source:
<code>public void onClusterProvisioned(ClusterProvisionedEvent event) { if (event.getClusterId() == getClusterId()) { LOG.info("Removing temporary configurations after successful deployment of cluster id={} name={}", getClusterId(), getClusterName()); for (Map.Entry<String, Set<String>> e : BlueprintConfigurationProcessor.TEMPORARY_PROPERTIES_FOR_CLUSTER_DEPLOYMENT.entrySet()) { try { configHelper.updateConfigType(this, getCurrentStackVersion(), controller, e.getKey(), Collections.emptyMap(), e.getValue(), "internal", "Removing temporary configurations after successful deployment" ); setBlueprintProvisioningState(BlueprintProvisioningState.FINISHED); <START> metadataHolder.updateData(controller.getClusterMetadataOnConfigsUpdate(this)); <END> LOG.info("Removed temporary configurations: / {}", e.getKey(), e.getValue()); } catch (AmbariException ex) { LOG.warn("Failed to remove temporary configurations: / {}", e.getKey(), e.getValue(), ex); } } } }</code><technical_language>This of for loop, more set of temporary properties. Code: Ideally logic onClusterProvisionStarted extracted a parametrized method, called states method</technical_language>

Target:
public void onClusterProvisioned(ClusterProvisionedEvent event) { if (event.getClusterId() == getClusterId()) { LOG.info("Removing temporary configurations after successful deployment of cluster id={} name={}", getClusterId(), getClusterName()); for (Map.Entry<String, Set<String>> e : BlueprintConfigurationProcessor.TEMPORARY_PROPERTIES_FOR_CLUSTER_DEPLOYMENT.entrySet()) { try { configHelper.updateConfigType(this, getCurrentStackVersion(), controller, e.getKey(), Collections.emptyMap(), e.getValue(), "internal", "Removing temporary configurations after successful deployment" ); LOG.info("Removed temporary configurations: / {}", e.getKey(), e.getValue()); } catch (AmbariException ex) { LOG.warn("Failed to remove temporary configurations: / {}", e.getKey(), e.getValue(), ex); } } changeBlueprintProvisioningState(BlueprintProvisioningState.FINISHED); } }
Source:
<code>public boolean isSearchIconClickable() { try { <START> return searchIconClickableLink.isDisplayed(); <END> } catch (NoSuchElementException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } }</code><technical_language>wait.forElementClickable element isDisplayed</technical_language>

Target:
public boolean isSearchIconClickable() { try { searchIconClickableLink.isDisplayed(); wait.forElementClickable(searchIconClickableLink, 0); return true; } catch (NoSuchElementException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } catch (TimeoutException e) { PageObjectLogging.logInfo(e.getMessage()); return false; } }
Source:
<code>public static void registerGcm(final Context context) { if (gcmRegistered) { return; } gcmRegistered = true; new Thread(() -> { try { @SuppressWarnings("deprecation") final String gcmRegistrationId = GoogleCloudMessaging.getInstance(context).register(GOOGLE_PUSH_SENDER_ID); if (Util.isNullOrEmpty(gcmRegistrationId)) { Lg.e("got empty gcm registration id from google server"); return; } if (!StorePushId.httpPostStorePushId(gcmRegistrationId)) { <START> Lg.e("ERROR: failed to store gcm push notification registration id=", gcmRegistrationId, " on simlar server"); <END> return; } Lg.i("gcm push notification registration id=", gcmRegistrationId, " stored on simlar server"); } catch (final IOException e) { Lg.ex(e, "gcm registration IOException"); } }).start(); }</code><technical_language>ERROR: redundant</technical_language>

Target:
public static void registerGcm(final Context context) { if (gcmRegistered) { return; } gcmRegistered = true; new Thread(() -> { try { @SuppressWarnings("deprecation") final String gcmRegistrationId = GoogleCloudMessaging.getInstance(context).register(GOOGLE_PUSH_SENDER_ID); if (Util.isNullOrEmpty(gcmRegistrationId)) { Lg.e("got empty gcm registration id from google server"); return; } if (!StorePushId.httpPostStorePushId(gcmRegistrationId)) { Lg.e("failed to store gcm push notification registration id=", gcmRegistrationId, " on simlar server"); return; } Lg.i("gcm push notification registration id=", gcmRegistrationId, " stored on simlar server"); } catch (final IOException e) { Lg.ex(e, "gcm registration IOException"); } }).start(); }
Source:
<code>protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); <START> if (proxy != null) <END> return (HttpURLConnection) url.openConnection(proxy); return (HttpURLConnection) url.openConnection(); }</code><technical_language>Please add curly braces {}, for single-line bodies. I know, code this, for new code require years. add change anyway, change other ifs in this source</technical_language>

Target:
protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); if (proxy != null) { return (HttpURLConnection) url.openConnection(proxy); } return (HttpURLConnection) url.openConnection(); }
Source:
<code>public boolean onTouch(View v, MotionEvent event) { boolean openUrl = ((WebContentDisplayScreenlet) getScreenlet()).onWebContentTouched(v, event); boolean isClick = event.getAction() == MotionEvent.ACTION_UP; if (!openUrl && isClick) { WebView.HitTestResult result = webView.getHitTestResult(); LiferayLogger.i("Event: " + event.toString()); LiferayLogger.i("Extra: " + result.getExtra()); ((WebContentDisplayScreenlet) getScreenlet()).onWebContentClicked(result); <START> return true; <END> } LiferayLogger.i("Open in browser: " + (openUrl ? "Yes" : "No")); return false; }</code><technical_language>Instead of returning true return result of listener call</technical_language>

Target:
public boolean onTouch(View v, MotionEvent event) { return ((WebContentDisplayScreenlet) getScreenlet()).onWebContentTouched(webView, event); }
Source:
<code>public void hibernateMigrate() throws DataMigrationException, XWikiException { <START> getStore().executeWrite(getXWikiContext(), new MigrateIVFCallback()); <END> }</code><technical_language>IVF in MigrateIVFCallback stands for in_vitro_fertilization / ivf, changed</technical_language>

Target:
public void hibernateMigrate() throws DataMigrationException, XWikiException { getStore().executeWrite(getXWikiContext(), new MigrateMoICallback()); }
Source:
<code>private void pingTaskNodeAndInitiateRestart(InternalTask task) { RunningTaskData runningTask = jobs.getRunningTask(task.getId()); if (runningTask != null) { Node nodeUsedToExecuteTask = runningTask.getNodeExecutor(); try { nodeUsedToExecuteTask.getNumberOfActiveObjects(); <START> long taskLauncherFailureTime = System.currentTimeMillis() - <END> runningTask.getFirstTaskLauncherFailureTime(); if (taskLauncherFailureTime > PASchedulerProperties.SCHEDULER_TASKLAUNCHER_PING_TIMEOUT.getValueAsLong()) { tlogger.error(task.getId(), "task launcher failed and was not accessible after " + taskLauncherFailureTime + " ms, initiate task restart."); runningTask.setRestarting(true); restartTaskOnNodeFailure(task); } } catch (Exception e) { int attempts = runningTask.increaseAndGetPingAttempts(); String nodeUrl = nodeUsedToExecuteTask.getNodeInformation().getURL(); if (attempts > PASchedulerProperties.SCHEDULER_NODE_PING_ATTEMPTS.getValueAsInt()) { tlogger.error(task.getId(), "node failed " + nodeUrl + ", initiate task restart.", e); runningTask.setRestarting(true); restartTaskOnNodeFailure(task); } else { tlogger.warn(task.getId(), "cannot contact node " + nodeUrl + " - waiting while it comes back, attempt " + attempts, e); } } } }</code><technical_language>factorized, runningTask.timeSinceFailure()</technical_language>

Target:
private void pingTaskNodeAndInitiateRestart(InternalTask task) { RunningTaskData runningTask = jobs.getRunningTask(task.getId()); if (runningTask != null) { Node nodeUsedToExecuteTask = runningTask.getNodeExecutor(); try { nodeUsedToExecuteTask.getNumberOfActiveObjects(); long taskLauncherFailureTime = runningTask.getTaskLauncherFailurePeriod(); if (taskLauncherFailureTime > PASchedulerProperties.SCHEDULER_TASKLAUNCHER_PING_TIMEOUT.getValueAsLong()) { tlogger.error(task.getId(), "task launcher failed and was not accessible after " + taskLauncherFailureTime + " ms, initiate task restart."); runningTask.setRestarting(); restartTaskOnNodeFailure(task); } } catch (Exception e) { int attempts = runningTask.increaseAndGetPingAttempts(); String nodeUrl = nodeUsedToExecuteTask.getNodeInformation().getURL(); if (attempts > PASchedulerProperties.SCHEDULER_NODE_PING_ATTEMPTS.getValueAsInt()) { tlogger.error(task.getId(), "node failed " + nodeUrl + ", initiate task restart.", e); runningTask.setRestarting(); restartTaskOnNodeFailure(task); } else { tlogger.warn(task.getId(), "cannot contact node " + nodeUrl + " - waiting while it comes back, attempt " + attempts, e); } } } }
Source:
<code>private BooleanExpression comparator(String operator, Object value) { <START> org.neo4j.cypherdsl.query.Query.checkNull( value, "Value" ); <END> return new Value( new Operator( identifier( alias ).property( propertyName ), operator ), literal( value ) ); }</code><technical_language>Contracts helper for this</technical_language>

Target:
private BooleanExpression comparator(String operator, Object value) { Contracts.assertNotNull( value, "Value" ); return new Value( new Operator( identifier( alias ).property( propertyName ), operator ), literal( value ) ); }
Source:
<code>public void detachCinderDomainFromPool(final StoragePoolIsoMap mapToRemove) { execute(new Callable<Object>() { @Override public Object call() { <START> DbFacade.getInstance() <END> .getStoragePoolIsoMapDao() .remove(new StoragePoolIsoMapId(mapToRemove.getstorage_id(), mapToRemove.getstorage_pool_id())); return null; } }); }</code><technical_language>external 'getStoragePoolIsoMapDAO()' method</technical_language>

Target:
public void detachCinderDomainFromPool(final StoragePoolIsoMap mapToRemove) { execute(new Callable<Object>() { @Override public Object call() { getStoragePoolIsoMapDAO().remove(new StoragePoolIsoMapId(mapToRemove.getstorage_id(), mapToRemove.getstorage_pool_id())); return null; } }); }
Source:
<code>public Response commitSnapshot(Action action) { RestoreAllSnapshotsParameters restoreParams = new RestoreAllSnapshotsParameters(guid, SnapshotActionEnum.COMMIT); <START> Response response = doAction(VdcActionType.RestoreAllSnapshots, <END> restoreParams, action); return response; }</code><technical_language>calling performAction() doAction()</technical_language>

Target:
public Response commitSnapshot(Action action) { RestoreAllSnapshotsParameters restoreParams = new RestoreAllSnapshotsParameters(guid, SnapshotActionEnum.COMMIT); Response response = performAction(VdcActionType.RestoreAllSnapshots, restoreParams, action); return response; }
Source:
<code>public DRConsumerDrIdTracker(JSONObject jsObj) throws JSONException { m_map = TreeRangeSet.create(); m_lastSpUniqueId = jsObj.getLong("spUniqueId"); m_lastMpUniqueId = jsObj.getLong("mpUniqueId"); final JSONArray drIdRanges = jsObj.getJSONArray("drIdRanges"); for (int ii = 0; ii < drIdRanges.length(); ii++) { JSONObject obj = drIdRanges.getJSONObject(ii); String startDrIdStr = obj.keys().next(); long start = Long.valueOf(startDrIdStr); long end = obj.getLong(startDrIdStr); if (start > end) { <START> throw new IllegalArgumentException(start + " after " + end); <END> } m_map.add(range(start, end)); } }</code><technical_language>I Range static constructor in range() validation already</technical_language>

Target:
public DRConsumerDrIdTracker(JSONObject jsObj) throws JSONException { m_map = TreeRangeSet.create(); m_lastSpUniqueId = jsObj.getLong("spUniqueId"); m_lastMpUniqueId = jsObj.getLong("mpUniqueId"); final JSONArray drIdRanges = jsObj.getJSONArray("drIdRanges"); for (int ii = 0; ii < drIdRanges.length(); ii++) { JSONObject obj = drIdRanges.getJSONObject(ii); String startDrIdStr = obj.keys().next(); m_map.add(range(Long.valueOf(startDrIdStr), obj.getLong(startDrIdStr))); } }
Source:
<code>private void fetch(Request.Builder requestBuilder, final Movie media, final Callback callback) { enqueue(requestBuilder.build(), new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); YSubsResponse result = mGson.fromJson(responseStr, YSubsResponse.class); <START> callback.onSuccess(result.formatForButte(PREFIX, LANGUAGE_MAPPING).get(media.imdbId)); <END> } } }); }</code><technical_language>callback.onSuccess(result.formatForButter(PREFIX,</technical_language>

Target:
private void fetch(Request.Builder requestBuilder, final Movie media, final Callback callback) { enqueue(requestBuilder.build(), new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onFailure(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); YSubsResponse result = mGson.fromJson(responseStr, YSubsResponse.class); callback.onSuccess(result.formatForButter(PREFIX, LANGUAGE_MAPPING).get(media.imdbId)); } } }); }
Source:
<code>public String toString() { <START> return "MeterReads{" + "logTime=" + logTime + ", activeEnergyImport=" + activeEnergyImport <END> + ", activeEnergyExport=" + activeEnergyExport + ", activeEnergyImportTariffOne=" + activeEnergyImportTariffOne + ", activeEnergyImportTariffTwo=" + activeEnergyImportTariffTwo + ", activeEnergyExportTariffOne=" + activeEnergyExportTariffOne + ", activeEnergyExportTariffTwo=" + activeEnergyExportTariffTwo + '}'; }</code><technical_language>"{" is object boundary, in other object.toString methods "[" is used</technical_language>

Target:
public String toString() { return "MeterReads [logTime=" + this.logTime + ", activeEnergyImport=" + this.activeEnergyImport + ", activeEnergyExport=" + this.activeEnergyExport + ", activeEnergyImportTariffOne=" + this.activeEnergyImportTariffOne + ", activeEnergyImportTariffTwo=" + this.activeEnergyImportTariffTwo + ", activeEnergyExportTariffOne=" + this.activeEnergyExportTariffOne + ", activeEnergyExportTariffTwo=" + this.activeEnergyExportTariffTwo + "]"; }
Source:
<code>public CharSequence[][] getHelpItems() { <START> return new CharSequence[][] { { getResources().getString(R.string.help_item_description) }, <END> { "<LINK_0>" } }; }</code><technical_language>@metalnow a bug, in Activity, call getString(...) directly</technical_language>

Target:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getString(R.string.help_item_description) }, { "<LINK_0>" } }; }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } <START> monthView.setEvents(this.events); <END> monthView.init(months.get(position), cells.get(position)); return monthView; }</code><technical_language>pass this in #init</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } monthView.init(months.get(position), cells.get(position)); return monthView; }
Source:
<code>protected abstract void startUp() throws Exception; protected abstract void runOneIteration() throws Exception; <START> protected void signal(@Nullable final Thread taskThread) throws Exception { <END> }</code><technical_language>nit: want rename signalShutdown this method called shutdown</technical_language>

Target:
protected abstract void startUp() throws Exception; protected abstract void runOneIteration() throws Exception; protected void signalShutdown(@Nullable final Thread taskThread) throws Exception { }
Source:
<code>public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() ) { LockSupport.park(); if ( Thread.interrupted() ) { <START> interrupted = true; <END> } } if ( interrupted ) { Thread.currentThread().interrupt(); } }</code><technical_language>If interrupted want return too, stuck in another park</technical_language>

Target:
public void submit(List<LuceneWork> workList, IndexingMonitor monitor) { Changeset changeset = new Changeset( workList, Thread.currentThread(), monitor ); transferQueue.add( changeset ); wakeUpConsumer(); boolean interrupted = false; while ( ! changeset.isProcessed() && ! interrupted ) { LockSupport.park(); if ( Thread.interrupted() ) { interrupted = true; } } if ( interrupted ) { Thread.currentThread().interrupt(); } }
Source:
<code>public void switchOffAdminMode() { <START> info("Switch OFF admin mode"); <END> if (isAdminModeOn()) { info("Admin mode is on. Switching it OFF"); getHeader().switchingAdminMode(); } info("Admin mode is switched OFF"); }</code><technical_language>Switching admin mode..</technical_language>

Target:
public void switchOffAdminMode() { info("Switching OFF admin mode..."); if (isAdminModeOn()) { info("Admin mode is on. Switching it OFF"); getHeader().switchingAdminMode(); } else { info("Admin mode was switched off already, doing nothing"); } info("Admin mode is switched OFF"); }
Source:
<code>public void initialize() { super.initialize(); eventBus.register(this); chatService.addChannelsListener(change -> { <START> if (change.wasRemoved() && !change.getValueRemoved().getName().endsWith("'sParty")) { <END> onChannelLeft(change.getValueRemoved()); } if (change.wasAdded() && !change.getValueAdded().getName().endsWith("'sParty")) { onChannelJoined(change.getValueAdded()); } }); JavaFxUtil.addListener(chatService.connectionStateProperty(), (observable, oldValue, newValue) -> onConnectionStateChange(newValue)); onConnectionStateChange(chatService.connectionStateProperty().get()); JavaFxUtil.addListener(tabPane.getTabs(), (ListChangeListener<Tab>) change -> { while (change.next()) { change.getRemoved().forEach(tab -> nameToChatTabController.remove(tab.getId())); } }); }</code><technical_language>Needs a constant</technical_language>

Target:
public void initialize() { super.initialize(); eventBus.register(this); chatService.addChannelsListener(change -> { if (change.wasRemoved() && !isMatchmakerPartyMessage(change.getValueRemoved().getName())) { onChannelLeft(change.getValueRemoved()); } if (change.wasAdded() && !isMatchmakerPartyMessage(change.getValueAdded().getName())) { onChannelJoined(change.getValueAdded()); } }); JavaFxUtil.addListener(chatService.connectionStateProperty(), (observable, oldValue, newValue) -> onConnectionStateChange(newValue)); onConnectionStateChange(chatService.connectionStateProperty().get()); JavaFxUtil.addListener(tabPane.getTabs(), (ListChangeListener<Tab>) change -> { while (change.next()) { change.getRemoved().forEach(tab -> nameToChatTabController.remove(tab.getId())); } }); }
Source:
<code>public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } <START> if(!shell.startsWith("/")) { <END> throw new WrongAttributeValueException(attribute, "Shell " + shell + " doesnt start with /"); } }</code><technical_language>This is covered line 524, it</technical_language>

Target:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } }