auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void startConnect(InetSocketAddress addr) throws IOException { saslLoginFailed = false; if (!isFirstConnect) { try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } if (!state.isAlive()) { throw new RuntimeException("Already closed"); } state = States.CONNECTING; String hostPort = addr.getHostString() + ":" + addr.getPort(); MDC.put("myid", hostPort); setName(getName().replaceAll("\\(.*\\)", "(" + hostPort + ")")); if (clientConfig.isSaslClientEnabled()) { try { if (zooKeeperSaslClient != null) { zooKeeperSaslClient.shutdown(); } zooKeeperSaslClient = new ZooKeeperSaslClient(SaslServerPrincipal.getServerPrincipal(addr, clientConfig), clientConfig); } catch (LoginException e) { LOG.warn( "SASL configuration failed. " + "Will continue connection to Zookeeper server without " + "SASL authentication, if Zookeeper server allows it.", e); eventThread.queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null)); saslLoginFailed = true; } } logStartConnect(addr); clientCnxnSocket.connect(addr); }

Target:
private void startConnect(InetSocketAddress addr) throws IOException { saslLoginFailed = false; if (!isFirstConnect) { try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } changeZkState(States.CONNECTING); String hostPort = addr.getHostString() + ":" + addr.getPort(); MDC.put("myid", hostPort); setName(getName().replaceAll("\\(.*\\)", "(" + hostPort + ")")); if (clientConfig.isSaslClientEnabled()) { try { if (zooKeeperSaslClient != null) { zooKeeperSaslClient.shutdown(); } zooKeeperSaslClient = new ZooKeeperSaslClient(SaslServerPrincipal.getServerPrincipal(addr, clientConfig), clientConfig); } catch (LoginException e) { LOG.warn( "SASL configuration failed. " + "Will continue connection to Zookeeper server without " + "SASL authentication, if Zookeeper server allows it.", e); eventThread.queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null)); saslLoginFailed = true; } } logStartConnect(addr); clientCnxnSocket.connect(addr); }
Source:
private synchronized Future closeSession(State finalState) { if (isClosed.compareAndSet(false, true)) { state(finalState); List<Future> futures = new ArrayList<>(); if (finalState == State.FAILED) futures.add(ScheduledExecutors.nonPeriodicTasks.submit(this::abortTasks)); logger.debug("[Stream #{}] Will close attached inbound channels {}", planId(), incomingChannels); incomingChannels.values().forEach(channel -> futures.add(channel.close())); messageSender.close(); streamResult.handleSessionComplete(this); closeFuture = FBUtilities.allOf(futures); } return closeFuture != null ? closeFuture : Futures.immediateFuture(null); }

Target:
private synchronized Future closeSession(State finalState) { if (closeFuture != null) return closeFuture; state(finalState); List<Future> futures = new ArrayList<>(); if (finalState == State.FAILED) futures.add(ScheduledExecutors.nonPeriodicTasks.submit(this::abortTasks)); if (!isFollower || state != State.COMPLETE) { logger.debug("[Stream #{}] Will close attached channels {}", planId(), channels); channels.values().forEach(channel -> futures.add(channel.close())); } sink.onClose(peer); streamResult.handleSessionComplete(this); closeFuture = FBUtilities.allOf(futures); return closeFuture; }
Source:
private static Druids.ScanQueryBuilder basicD(final BenchmarkSchemaInfo basicSchema) { final QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(basicSchema.getDataInterval()) ); final List<String> dimUniformFilterVals = new ArrayList<>(); final int resultNum = (int) (100000 * 0.1); final int step = 100000 / resultNum; for (int i = 1; i < 100001 && dimUniformFilterVals.size() < resultNum; i += step) { dimUniformFilterVals.add(String.valueOf(i)); } final String dimName = "dimUniform"; return Druids.newScanQueryBuilder() .filters(new BoundDimFilter(dimName, "100", "10000", true, true, true, null, null)) .intervals(intervalSpec); }

Target:
private static Druids.ScanQueryBuilder basicD(final BenchmarkSchemaInfo basicSchema) { final QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec( Collections.singletonList(basicSchema.getDataInterval()) ); final String dimName = "dimUniform"; return Druids.newScanQueryBuilder() .filters(new BoundDimFilter(dimName, "100", "10000", true, true, true, null, null)) .intervals(intervalSpec); }
Source:
protected DefaultHttpClient httpClient(final String repositoryURL) { if ( clients.size() > 0 ) { for ( final Iterator<String> it = clients.keySet().iterator(); it.hasNext(); ) { final String base = it.next(); if ( repositoryURL.startsWith(base) ) { return clients.get(base); } } } if ( defaultClient != null ) { return defaultClient; } final String baseURL; if ( repositoryURL.indexOf("/rest/") > 0 ) { baseURL = repositoryURL.substring(0, repositoryURL.indexOf("/rest/") + 6); } else if ( repositoryURL.indexOf("/",8) > 0 ) { baseURL = repositoryURL.substring(0, repositoryURL.indexOf("/",8) + 1); } else { baseURL = repositoryURL; } final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager(); connMann.setMaxTotal(MAX_VALUE); connMann.setDefaultMaxPerRoute(MAX_VALUE); final DefaultHttpClient httpClient = new DefaultHttpClient(connMann); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false)); if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) { LOGGER.debug("Adding BASIC credentials to client for repo requests."); final URI fedoraUri = URI.create(baseURL); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()), new UsernamePasswordCredentials(fedoraUsername, fedoraPassword)); httpClient.setCredentialsProvider(credsProvider); } clients.put(baseURL, httpClient); return httpClient; }

Target:
protected DefaultHttpClient httpClient(final String repositoryURL) { if ( clients.size() > 0 ) { for ( final Iterator<String> it = clients.keySet().iterator(); it.hasNext(); ) { final String base = it.next(); if ( repositoryURL.startsWith(base) ) { return clients.get(base); } } } if ( defaultClient != null ) { return defaultClient; } final String baseURL; if ( repositoryURL.indexOf(REST_PREFIX) > 0 ) { baseURL = repositoryURL.substring(0, repositoryURL.indexOf(REST_PREFIX) + REST_PREFIX.length()); } else if ( repositoryURL.indexOf("/",FCREPO_PREFIX.length()) > 0 ) { baseURL = repositoryURL.substring(0, repositoryURL.indexOf("/",FCREPO_PREFIX.length()) + 1); } else { baseURL = repositoryURL; } final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager(); connMann.setMaxTotal(MAX_VALUE); connMann.setDefaultMaxPerRoute(MAX_VALUE); final DefaultHttpClient httpClient = new DefaultHttpClient(connMann); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false)); if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) { LOGGER.debug("Adding BASIC credentials to client for repo requests."); final URI fedoraUri = URI.create(baseURL); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()), new UsernamePasswordCredentials(fedoraUsername, fedoraPassword)); httpClient.setCredentialsProvider(credsProvider); } clients.put(baseURL, httpClient); return httpClient; }
Source:
public Optional<ResponseBody> convert(ResponseBody value) { return Optional.ofNullable(value); }

Target:
public Optional<ResponseBody> convert(ResponseBody value) { return Optional.of(value); }
Source:
public HostListCommand(final Subparser parser) { super(parser); parser.help("list hosts"); patternArg = parser.addArgument("pattern") .nargs("?") .setDefault("") .help("Pattern to filter hosts with"); quietArg = parser.addArgument("-q") .action(storeTrue()) .help("only print host names"); fullArg = parser.addArgument("-f") .action(storeTrue()) .help("Print full host names."); statusArg = parser.addArgument("--status") .nargs("?") .help("Filter hosts by its status, i.e. \"UP\" or \"DOWN\"."); labelsArg = parser.addArgument("-l", "--labels") .action(append()) .setDefault(new ArrayList<String>()) .nargs("+") .help("Only include hosts that match all of these labels. Labels need to be in the format " + "key=value."); }

Target:
public HostListCommand(final Subparser parser) { super(parser); Collection<String> statusChoices = Collections2.transform( Arrays.asList(HostStatus.Status.values()), new Function<HostStatus.Status, String>() { @Override public String apply(final HostStatus.Status input) { return input.toString(); } }); statusChoicesString = Joiner.on(", ").join(statusChoices); parser.help("list hosts"); patternArg = parser.addArgument("pattern") .nargs("?") .setDefault("") .help("Pattern to filter hosts with"); quietArg = parser.addArgument("-q") .action(storeTrue()) .help("only print host names"); fullArg = parser.addArgument("-f") .action(storeTrue()) .help("Print full host names."); statusArg = parser.addArgument("--status") .nargs("?") .choices(statusChoices.toArray(new String[statusChoices.size()])) .help("Filter hosts by its status. Valid statuses are: " + statusChoicesString); labelsArg = parser.addArgument("-l", "--labels") .action(append()) .setDefault(new ArrayList<String>()) .nargs("+") .help("Only include hosts that match all of these labels. Labels need to be in the format " + "key=value."); }
Source:
public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } Map<String, Integer> answerFrequency = new LinkedHashMap<String, Integer>(); int numChoicesSelected = getNumberOfResponses(responses, answerFrequency); if (numChoicesSelected == -1) { return ""; } DecimalFormat df = new DecimalFormat("#.##"); StringBuilder fragments = new StringBuilder(); for (Entry<String, Integer> entry : answerFrequency.entrySet()) { fragments.append(SanitizationHelper.sanitizeForCsv(entry.getKey()) + ',' + entry.getValue().toString() + ',' + df.format(100 * divideOrReturnZero((double) entry.getValue(), numChoicesSelected)) + Const.EOL); } return "Choice, Response Count, Percentage" + Const.EOL + fragments + Const.EOL; }

Target:
public String getQuestionResultStatisticsCsv( List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, FeedbackSessionResultsBundle bundle) { if (responses.isEmpty()) { return ""; } Map<String, Integer> answerFrequency = new LinkedHashMap<String, Integer>(); int numChoicesSelected = getNumberOfResponses(responses, answerFrequency); if (numChoicesSelected == -1) { return ""; } DecimalFormat df = new DecimalFormat("#.##"); StringBuilder fragments = new StringBuilder(); for (Entry<String, Integer> entry : answerFrequency.entrySet()) { fragments.append(SanitizationHelper.sanitizeForCsv(entry.getKey()) + ',' + entry.getValue().toString() + ',' + df.format(100 * divideOrReturnZero(entry.getValue(), numChoicesSelected)) + Const.EOL); } return "Choice, Response Count, Percentage" + Const.EOL + fragments + Const.EOL; }
Source:
public synchronized static DbFacade getDbFacade() { if (dbFacade != null) { return dbFacade; } loadDbFacadeConfig(); DbEngineDialect dialect = loadDbEngineDialect(); long timeStarted = System.currentTimeMillis(); DataSource datasource = null; for (;;) { datasource = EjbUtils.findResource(ContainerManagedResourceType.DATA_SOURCE); if (datasource != null) { break; } long timeNow = System.currentTimeMillis(); long timeWaited = timeNow - timeStarted; if (timeWaited > connectionTimeout) { log.errorFormat( "The data source can't be located after wating for more " + "than {0} seconds, giving up.", connectionTimeout / 1000 ); return null; } log.warnFormat( "The data source can't be located after waiting for {0} " + "seconds, will try again.", timeWaited / 1000 ); try { Thread.sleep(checkInterval); } catch (InterruptedException exception) { log.warnFormat( "Interrupted while waiting for data source.", exception ); } } dbFacade = new DbFacade(); dbFacade.setOnStartConnectionTimeout(connectionTimeout); dbFacade.setConnectionCheckInterval(checkInterval); dbFacade.setDbEngineDialect(dialect); JdbcTemplate jdbcTemplate = dialect.createJdbcTemplate(datasource); SQLErrorCodeSQLExceptionTranslator tr = new CustomSQLErrorCodeSQLExceptionTranslator(datasource); jdbcTemplate.setExceptionTranslator(tr); dbFacade.setTemplate(jdbcTemplate); return dbFacade; }

Target:
public static DbFacade getDbFacade() { if (dbFacade == null) { synchronized(DbFacadeLocator.class) { if (dbFacade == null) { dbFacade = createDbFacade(); } } } return dbFacade; }
Source:
public void shouldShowMyResourcesAndRemoveShares() { final int row = 2; myResourcesPage.clickExpandButton(row); assertEquals("Resource is shared with alice.", myResourcesPage.getSharedWith(row)); myResourcesPage.clickRemoveButton(row); myResourcesPage.clickExpandButton(row); myResourcesPage.alert().assertSuccess(); assertEquals("This resource is not shared.", myResourcesPage.getSharedWith(row)); }

Target:
public void shouldShowMyResourcesAndRemoveShares() { final int row = 2; myResourcesPage.clickExpandButton(row); testModalDialog(() -> myResourcesPage.clickRemoveButton(row), () -> assertEquals("Resource is shared with alice.", myResourcesPage.getSharedWith(row))); myResourcesPage.alert().assertSuccess(); assertEquals("This resource is not shared.", myResourcesPage.getSharedWith(row)); }
Source:
protected URI rewriteURI(HttpServletRequest request) { final StringBuilder uri = new StringBuilder(request.getScheme()); uri.append("://"); uri.append(selector.pick().getHost()); uri.append(request.getRequestURI()); final String queryString = request.getQueryString(); if (queryString != null) { uri.append("?").append(queryString); } return URI.create(uri.toString()); }

Target:
protected URI rewriteURI(HttpServletRequest request) { try { final Server indexer = selector.pick(); if (indexer == null) { throw new ISE("Cannot find instance of indexingService"); } return new URI( request.getScheme(), indexer.getHost(), request.getRequestURI(), request.getQueryString(), null ); } catch (URISyntaxException e) { throw Throwables.propagate(e); } }
Source:
public BasePostsCreator startPostCreationWith(String description) { click() .closeGuidelinesMessage() .addTitleWith(TextGenerator.defaultText()) .addDescriptionWith(description) .clickAddCategoryButton() .selectFirstCategory(); return this; }

Target:
public BasePostsCreator startPostCreationWith(String description) { startPostCreationWithoutDescription() .addDescriptionWith(description); return this; }
Source:
public Serializable toPersistedValue(@Nullable Object columnValue) { if (columnValue == null) { return null; } checkTypeMatches(columnValue); return valuePersistor.toPersistedValue(columnValue); }

Target:
public Serializable toPersistedValue(@Nullable Object columnValue) { if (columnValue == null) { return null; } checkTypeMatches(columnValue); return valueConverter.convert(columnValue); }
Source:
private OrcBatchRecordReader createRecordReader() throws IOException { OrcDataSource dataSource = new FileOrcDataSource(orcFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( dataSource, ORC, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), OrcReaderTestingUtils.createDefaultTestConfig(), new HiveFileContext(false, Optional.empty())); return orcReader.createBatchRecordReader( ImmutableMap.of(0, type), OrcPredicate.TRUE, UTC, newSimpleAggregatedMemoryContext(), INITIAL_BATCH_SIZE); }

Target:
private OrcBatchRecordReader createRecordReader() throws IOException { OrcDataSource dataSource = new FileOrcDataSource(orcFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( dataSource, ORC, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), OrcReaderTestingUtils.createDefaultTestConfig(), DEFAULT_HIVE_FILE_CONTEXT); return orcReader.createBatchRecordReader( ImmutableMap.of(0, type), OrcPredicate.TRUE, UTC, newSimpleAggregatedMemoryContext(), INITIAL_BATCH_SIZE); }
Source:
protected AbstractSegmentStoreTableViewer createSegmentStoreTableViewer(Composite parent) { return new FunctionTableViewer(new TableViewer(parent, SWT.FULL_SELECTION | SWT.VIRTUAL), getViewSite().getSecondaryId()) { @Override protected void createProviderColumns() { super.createProviderColumns(); Table t = (Table) getControl(); moveColumnTo(t, SegmentDurationAspect.SEGMENT_DURATION_ASPECT.getName(), 0); moveColumnTo(t, SegmentStartTimeAspect.SEGMENT_START_TIME_ASPECT.getName(), 1); moveColumnTo(t, SegmentEndTimeAspect.SEGMENT_END_TIME_ASPECT.getName(), 2); } private void moveColumnTo(Table t, String aspectName, int desiredIndex) { int[] order = t.getColumnOrder(); int foundIndex = -1; for(int i = 0 ; i < t.getColumnCount(); i++) { TableColumn col = t.getColumn(i); if(col.getText().equals(aspectName)) { foundIndex = i; } } int tmp = order[desiredIndex]; order[desiredIndex] = order[foundIndex]; order[foundIndex] = tmp; t.setColumnOrder(order); } }; }

Target:
protected AbstractSegmentStoreTableViewer createSegmentStoreTableViewer(Composite parent) { return new FunctionTableViewer(new TableViewer(parent, SWT.FULL_SELECTION | SWT.VIRTUAL), getViewSite().getSecondaryId()) { @Override protected void createProviderColumns() { super.createProviderColumns(); Table t = (Table) getControl(); moveColumnTo(t, SegmentDurationAspect.SEGMENT_DURATION_ASPECT.getName(), 0); moveColumnTo(t, SegmentStartTimeAspect.SEGMENT_START_TIME_ASPECT.getName(), 1); moveColumnTo(t, SegmentEndTimeAspect.SEGMENT_END_TIME_ASPECT.getName(), 2); } private void moveColumnTo(Table t, String aspectName, int desiredIndex) { int[] order = t.getColumnOrder(); int foundIndex = -1; for (int i = 0 ; i < t.getColumnCount(); i++) { TableColumn col = t.getColumn(i); if(col.getText().equals(aspectName)) { foundIndex = i; } } if (index == -1) { return; } int tmp = order[desiredIndex]; order[desiredIndex] = order[foundIndex]; order[foundIndex] = tmp; t.setColumnOrder(order); } }; }
Source:
private void handle(HttpServletRequest req, HttpServletResponse res) throws IOException { try { Tokens tokens = controller.handle(req); TokenAuthentication tokenAuth = new TokenAuthentication(JWT.decode(tokens.getIdToken())); Authentication authentication = GoogleAccountsAuthenticationProvider.getAuthentication( false, new UserDao(), tokenAuth, tokenAuth.getClaims().get("email").asString(), tokenAuth.getClaims().get("nickname").asString() ); SecurityContextHolder.getContext().setAuthentication(authentication); res.sendRedirect(redirectOnSuccess); } catch (AuthenticationException | IdentityVerificationException e) { String errorDescriptionId = "error_description"; String errorDescription= req.getParameter(errorDescriptionId); log.log(Level.SEVERE, errorDescriptionId+": "+errorDescription+" Error Message: "+e.getMessage()); SecurityContextHolder.clearContext(); if(errorDescription != null){ res.sendRedirect(redirectOnFail+"?errorCode="+errorDescription); }else{ res.sendRedirect(redirectOnFail); } } }

Target:
private void handle(HttpServletRequest req, HttpServletResponse res) throws IOException { try { Tokens tokens = controller.handle(req); TokenAuthentication tokenAuth = new TokenAuthentication(JWT.decode(tokens.getIdToken())); Authentication authentication = GoogleAccountsAuthenticationProvider.getAuthentication( false, new UserDao(), tokenAuth, tokenAuth.getClaims().get("email").asString(), tokenAuth.getClaims().get("nickname").asString() ); SecurityContextHolder.getContext().setAuthentication(authentication); res.sendRedirect(redirectOnSuccess); } catch (AuthenticationException | IdentityVerificationException e) { String errorDescriptionId = "error_description"; String errorDescription = req.getParameter(errorDescriptionId); log.log(getLogLevel(errorDescription), errorDescriptionId + ": " + errorDescription + " Error Message: " + e.getMessage()); SecurityContextHolder.clearContext(); res.sendRedirect(redirectOnFail + "?errorCode=" + errorDescription); } }
Source:
public boolean isJobExecutionComplete() { return execution != null && execution.getStatus().compareTo(BatchStatus.COMPLETED) == 0 && execution.getExitStatus().compareTo(ExitStatus.COMPLETED) == 0; }

Target:
public boolean isJobExecutionComplete() { return execution != null && execution.getStatus().equals(BatchStatus.COMPLETED) && execution.getExitStatus().compareTo(ExitStatus.COMPLETED) == 0; }
Source:
public Trace getTraceFragment(String tenantId, String id) { Span span = getSpan(tenantId, id); Trace trace = spanToTrace(span); LinkedList<Node> nodes = recursiveTraceFragment(tenantId, id); nodes.push(spanToNode(span)); trace.setNodes(nodes); return trace; }

Target:
public Trace getTraceFragment(String tenantId, String id) { Span span = getSpan(tenantId, id); if (span == null) { return null; } InteractionNode interactionNode = spanToNode(span); interactionNode.setNodes(recursiveTraceFragment(tenantId, span)); Trace trace = spanToTrace(span); trace.getNodes().add(interactionNode); return trace; }
Source:
public LargestSeriesProductCalculator(String inputNumber) { throw new UnsupportedOperationException ("Delete this statement and write your own implementation."); }

Target:
LargestSeriesProductCalculator(String inputNumber) { throw new UnsupportedOperationException ("Delete this statement and write your own implementation."); }
Source:
void fun() { int i = nextInt(); Random random = new Random(); byte[] bytes = new byte[20]; random.nextBytes(bytes); double rand1 = Math.random(); double abs = Math.abs(12); int rand2 = ThreadLocalRandom.current().nextInt(); JVMRandom jvmRandom = new JVMRandom(); double rand3 = jvmRandom.nextDouble(); RandomUtils randomUtils = new RandomUtils(); float rand4 = randomUtils.nextFloat(); float rand5 = RandomUtils.nextFloat(); org.apache.commons.lang3.RandomUtils randomUtils2 = new org.apache.commons.lang3.RandomUtils(); float rand6 = randomUtils2.nextFloat(); float rand7 = org.apache.commons.lang3.RandomUtils.nextFloat(); RandomStringUtils randomStringUtils = new RandomStringUtils(); String rand8 = randomStringUtils.random(1); String rand9 = RandomStringUtils.random(1); org.apache.commons.lang3.RandomStringUtils randomStringUtils2 = new org.apache.commons.lang3.RandomStringUtils(); String rand10 = randomStringUtils.random(1); String rand11 = org.apache.commons.lang3.RandomStringUtils.random(1); }

Target:
void fun() { int i = nextInt(); Random random = new Random(); byte[] bytes = new byte[20]; random.nextBytes(bytes); JVMRandom jvmRandom = new JVMRandom(); double rand3 = jvmRandom.nextDouble(); double rand1 = Math.random(); double abs = Math.abs(12); int rand2 = ThreadLocalRandom.current().nextInt(); RandomUtils randomUtils = new RandomUtils(); float rand4 = randomUtils.nextFloat(); float rand5 = RandomUtils.nextFloat(); org.apache.commons.lang3.RandomUtils randomUtils2 = new org.apache.commons.lang3.RandomUtils(); float rand6 = randomUtils2.nextFloat(); float rand7 = org.apache.commons.lang3.RandomUtils.nextFloat(); RandomStringUtils randomStringUtils = new RandomStringUtils(); String rand8 = randomStringUtils.random(1); String rand9 = RandomStringUtils.random(1); org.apache.commons.lang3.RandomStringUtils randomStringUtils2 = new org.apache.commons.lang3.RandomStringUtils(); String rand10 = randomStringUtils.random(1); String rand11 = org.apache.commons.lang3.RandomStringUtils.random(1); }
Source:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(httpEx.responseBody + ""); log.log("<--- END MOCK"); } } }

Target:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(String.valueOf(httpEx.responseBody)); log.log("<--- END MOCK"); } } }
Source:
public void matchWildcardIdentifier() { ErrorType wildcardErrorType = ErrorTypeBuilder.builder().namespace(CORE_NAMESPACE_NAME).identifier(WILDCARD_TOKEN) .parentErrorType(transformationErrorType).build(); ErrorType test1ErrorType = ErrorTypeBuilder.builder().namespace(CORE_NAMESPACE_NAME).identifier("test1") .parentErrorType(transformationErrorType).build(); ErrorType test2ErrorType = ErrorTypeBuilder.builder().namespace(CORE_NAMESPACE_NAME).identifier("test2") .parentErrorType(transformationErrorType).build(); ErrorType test3ErrorType = ErrorTypeBuilder.builder().namespace("unknown").identifier("test3").parentErrorType(transformationErrorType).build(); ErrorTypeMatcher wildcardMatcher = new WildcardErrorTypeMatcher(wildcardErrorType); assertThat(wildcardMatcher.match(test1ErrorType), is(true)); assertThat(wildcardMatcher.match(test2ErrorType), is(true)); assertThat(wildcardMatcher.match(test3ErrorType), is(false)); }

Target:
public void matchWildcardIdentifier() { ComponentIdentifier wildcardErrorType = buildFromStringRepresentation(CORE_NAMESPACE_NAME + ":" + WILDCARD_TOKEN); ErrorType test1ErrorType = ErrorTypeBuilder.builder().namespace(CORE_NAMESPACE_NAME).identifier("test1") .parentErrorType(transformationErrorType).build(); ErrorType test2ErrorType = ErrorTypeBuilder.builder().namespace(CORE_NAMESPACE_NAME).identifier("test2") .parentErrorType(transformationErrorType).build(); ErrorTypeMatcher wildcardMatcher = new WildcardErrorTypeMatcher(wildcardErrorType); assertThat(wildcardMatcher.match(test1ErrorType), is(true)); assertThat(wildcardMatcher.match(test2ErrorType), is(true)); }
Source:
public void testCreateReadDelete() throws Exception { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", "Foo"); userModel = userManager.createUser(userModel); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); folder = systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACE grantRead = new ACE("Foo", SecurityConstants.READ, true); acp.addACE(ACL.LOCAL_ACL, grantRead); doc.setACP(acp, true); try (CoreSession userSession = coreFeature.openCoreSession("Foo")) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setProperty("comment", "text", "This is my comment"); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query("SELECT * FROM " + CommentsConstants.COMMENT_DOC_TYPE); assertEquals(1, dml.size()); dml = userSession.query("SELECT * FROM " + CommentsConstants.COMMENT_DOC_TYPE); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }

Target:
public void testCreateReadDelete() { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACE grantRead = new ACE(USERNAME, SecurityConstants.READ, true); acp.addACE(ACL.LOCAL_ACL, grantRead); doc.setACP(acp, true); try (CoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }
Source:
protected void release(boolean wait, boolean writer) { final int refCount = this.refCount.decrementAndGet(); if (canEvict(refCount, writer)) { assert (next != null); final Runnable storer = getStorer(data, readingOffset, writingOffset, storage); if (future != null && future.cancel(false)) { logger.debug("Block future is cancelled", this); } final int numberOfInMemBlockPermits = DataList.this.numberOfInMemBlockPermits.get(); if (wait && numberOfInMemBlockPermits == 0) { future = null; storer.run(); } else if (numberOfInMemBlockPermits < MAX_COUNT_OF_INMEM_BLOCKS / 2) { future = storageExecutor.submit(storer); } else { future = null; } } else if (storage == null) { resumeSuspendedClients(-1); } }

Target:
protected void release(boolean wait, boolean writer) { final int refCount = this.refCount.decrementAndGet(); if (canEvict(refCount, writer)) { assert (next != null); if (storage != null) { evictBlock(wait); } else { if (!isPublisherAheadByMax()) { resumeSuspendedClients(); } } } }
Source:
public void testPollAndResponseHandling() throws Exception { NonBlockingRouter.currentOperationsCount.incrementAndGet(); GetBlobInfoOperation op = new GetBlobInfoOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobIdStr, options, null, routerCallback, kms, cryptoService, cryptoJobHandler, time); ArrayList<RequestInfo> requestListToFill = new ArrayList<>(); requestRegistrationCallback.requestListToFill = requestListToFill; op.poll(requestRegistrationCallback); Assert.assertEquals("There should only be as many requests at this point as requestParallelism", requestParallelism, correlationIdToGetOperation.size()); List<ResponseInfo> responses = sendAndWaitForResponses(requestListToFill); for (ResponseInfo responseInfo : responses) { GetResponse getResponse = responseInfo.getError() == null ? GetResponse.readFrom( new DataInputStream(new ByteBufferInputStream(responseInfo.getResponse())), mockClusterMap) : null; op.handleResponse(responseInfo, getResponse); if (op.isOperationComplete()) { break; } } if (testEncryption) { int timeout = 1000; int timeSoFar = 0; while (timeSoFar < timeout && !op.isOperationComplete()) { op.poll(requestRegistrationCallback); Thread.sleep(10); timeSoFar += 10; } } Assert.assertTrue("Operation should be complete at this time", op.isOperationComplete()); assertSuccess(op); }

Target:
public void testPollAndResponseHandling() throws Exception { NonBlockingRouter.currentOperationsCount.incrementAndGet(); GetBlobInfoOperation op = new GetBlobInfoOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobIdStr, options, null, routerCallback, kms, cryptoService, cryptoJobHandler, time); ArrayList<RequestInfo> requestListToFill = new ArrayList<>(); requestRegistrationCallback.requestListToFill = requestListToFill; op.poll(requestRegistrationCallback); Assert.assertEquals("There should only be as many requests at this point as requestParallelism", requestParallelism, correlationIdToGetOperation.size()); CountDownLatch onPollLatch = new CountDownLatch(1); if (testEncryption) { routerCallback.setOnPollLatch(onPollLatch); } List<ResponseInfo> responses = sendAndWaitForResponses(requestListToFill); for (ResponseInfo responseInfo : responses) { GetResponse getResponse = responseInfo.getError() == null ? GetResponse.readFrom( new DataInputStream(new ByteBufferInputStream(responseInfo.getResponse())), mockClusterMap) : null; op.handleResponse(responseInfo, getResponse); if (op.isOperationComplete()) { break; } } if (testEncryption) { Assert.assertTrue("Latch should have been zeroed ", onPollLatch.await(500, TimeUnit.MILLISECONDS)); op.poll(requestRegistrationCallback); } Assert.assertTrue("Operation should be complete at this time", op.isOperationComplete()); assertSuccess(op); }
Source:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), messageType); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_TARIFF_SWITCHING, "An unknown error occurred", e); } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }

Target:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.info("handeling error: for message type: {}", e.getMessage(), messageType); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_TARIFF_SWITCHING, "An unknown error occurred", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
private HttpURLConnection connect(final String service) throws TransportException, NotSupportedException { final URL u; try { final StringBuilder b = new StringBuilder(); b.append(baseUrl); if (b.charAt(b.length() - 1) != '/') b.append('/'); b.append(Constants.INFO_REFS); if (useSmartHttp) { b.append(b.indexOf("?") < 0 ? '?' : '&'); b.append("service="); b.append(service); } u = new URL(b.toString()); } catch (MalformedURLException e) { throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e); } try { final HttpURLConnection conn = httpOpen(u); if (useSmartHttp) { String expType = "application/x-" + service + "-advertisement"; conn.setRequestProperty(HDR_ACCEPT, expType + ", * *"); } final int status = HttpSupport.response(conn); switch (status) { case HttpURLConnection.HTTP_OK: return conn; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoRemoteRepositoryException(uri, MessageFormat.format(JGitText.get().URLNotFound, u)); case HttpURLConnection.HTTP_FORBIDDEN: throw new TransportException(uri, MessageFormat.format(JGitText.get().serviceNotPermitted, service)); default: String err = status + " " + conn.getResponseMessage(); throw new TransportException(uri, err); } } catch (NotSupportedException e) { throw e; } catch (TransportException e) { throw e; } catch (IOException e) { throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpen, service), e); } }

Target:
private HttpURLConnection connect(final String service) throws TransportException, NotSupportedException { final URL u; try { final StringBuilder b = new StringBuilder(); b.append(baseUrl); if (b.charAt(b.length() - 1) != '/') b.append('/'); b.append(Constants.INFO_REFS); if (useSmartHttp) { b.append(b.indexOf("?") < 0 ? '?' : '&'); b.append("service="); b.append(service); } u = new URL(b.toString()); } catch (MalformedURLException e) { throw new NotSupportedException(MessageFormat.format(JGitText.get().invalidURL, uri), e); } try { final HttpURLConnection conn = httpOpen(u); if (useSmartHttp) { String expType = "application/x-" + service + "-advertisement"; conn.setRequestProperty(HDR_ACCEPT, expType + ", * *"); } final int status = HttpSupport.response(conn); switch (status) { case HttpURLConnection.HTTP_OK: return conn; case HttpURLConnection.HTTP_NOT_FOUND: throw new NoRemoteRepositoryException(uri, MessageFormat.format(JGitText.get().URLNotFound, u)); case HttpURLConnection.HTTP_FORBIDDEN: throw new TransportException(uri, MessageFormat.format(JGitText.get().serviceNotPermitted, service)); default: String err = status + " " + conn.getResponseMessage(); throw new TransportException(uri, err); } } catch (NotSupportedException e) { throw e; } catch (TransportException e) { throw e; } catch (IOException e) { throw new TransportException(uri, MessageFormat.format(JGitText.get().cannotOpenService, service), e); } }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PhoenixJson other = (PhoenixJson) obj; if ((this.jsonAsString != null) && (other.jsonAsString != null)) { if (this.jsonAsString.equals(other.jsonAsString)) return true; } if (this.rootNode == null) { if (other.rootNode != null) return false; } else if (!this.rootNode.equals(other.rootNode)) return false; return true; }

Target:
public boolean equals(Object obj) { throw new EqualityNotSupportedException(PJson.INSTANCE); }
Source:
public synchronized boolean isOpen() { return true; }

Target:
public boolean isOpen() { return true; }
Source:
void testWhenResultEventDataIsNullThenNoUtilizerCallHappens() { AttemptAuditEventResult source = makeMinimalAttemptAuditEventResult(null); underTest.convert(source); verify(mockAuditEventDataUtilizer, times(0)).modifyAuditEventBuilderWithEventData(any(), any()); }

Target:
void testWhenResultEventDataIsNullThenNoUtilizerCallHappens() { AttemptAuditEventResult source = makeMinimalAttemptAuditEventResult(null); underTest.convert(source); verify(mockAttemptAuditEventResultBuilderUpdater, never()).update(any(), any()); }
Source:
public void onRoutingTableChange() { rwlock1.readLock().lock(); try { for (String partitionName : peerLeaderReplicasByPartition.keySet()) { ReplicaId localLeaderReplica = storeManager.getReplica(partitionName); PartitionId partition = localLeaderReplica.getPartitionId(); List<ReplicaId> currentRemoteLeaderReplicas = peerLeaderReplicasByPartition.get(partitionName); List<ReplicaId> updatedRemoteLeaderReplicas = partition.getReplicaIdsByState(ReplicaState.LEADER, null) .stream() .filter(r -> !r.getDataNodeId().getDatacenterName().equals(dataNodeId.getDatacenterName())) .collect(Collectors.toList()); Set<ReplicaId> addedRemoteReplicas = new HashSet<>(updatedRemoteLeaderReplicas); addedRemoteReplicas.removeAll(currentRemoteLeaderReplicas); Set<ReplicaId> removedRemoteReplicas = new HashSet<>(currentRemoteLeaderReplicas); removedRemoteReplicas.removeAll(updatedRemoteLeaderReplicas); for (ReplicaId remoteReplica : addedRemoteReplicas) { logger.info("Adding new remote leader for Partition to replicate from dc {}", getInstanceName(remoteReplica.getDataNodeId().getHostname(), remoteReplica.getDataNodeId().getPort()), partitionName, remoteReplica.getDataNodeId().getDatacenterName()); } List<RemoteReplicaInfo> replicaInfosToRemove = new ArrayList<>(); for (ReplicaId remoteReplica : removedRemoteReplicas) { logger.info("Removing old remote leader for Partition from dc {}", getInstanceName(remoteReplica.getDataNodeId().getHostname(), remoteReplica.getDataNodeId().getPort()), partitionName, remoteReplica.getDataNodeId().getDatacenterName()); } peerLeaderReplicasByPartition.put(partitionName, updatedRemoteLeaderReplicas); } } finally { rwlock1.readLock().unlock(); } }

Target:
public void onRoutingTableChange() { try { startupLatch.await(); } catch (InterruptedException e) { logger.warn("Waiting for startup is interrupted."); throw new IllegalStateException( "Replication manager startup is interrupted while handling routing table change"); } partitionLeaderInfo.refreshPeerLeadersForAllPartitions(); }
Source:
public void testLongFixedSizeRangeFieldPartitionerRangePredicate() { final FieldPartitioner<Long, Long> fp = new LongFixedSizeRangeFieldPartitioner("num", 5); Assert.assertEquals(Ranges.closed(-5L, 10L), fp.project(Ranges.open(-2L, 15L))); Assert.assertEquals(Ranges.closed(5L, 10L), fp.project(Ranges.open(5L, 15L))); Assert.assertEquals(Ranges.closed(5L, 10L), fp.project(Ranges.open(4L, 15L))); Assert.assertEquals(Ranges.closed(0L, 15L), fp.project(Ranges.closed(4L, 15L))); Assert.assertEquals(Ranges.closed(5L, 20L), fp.project(Ranges.openClosed(5L, 21L))); Assert.assertEquals(Ranges.singleton(10L), fp.projectStrict(Ranges.open(5L, 15L))); Assert.assertNull(fp.projectStrict(Ranges.open(5L, 14L))); Assert.assertEquals(Ranges.atMost(10L), fp.projectStrict(Ranges.atMost(15L))); Assert.assertEquals(Ranges.atMost(15L), fp.projectStrict(Ranges.lessThan(21L))); Assert.assertEquals(Ranges.atLeast(15L), fp.projectStrict(Ranges.atLeast(14L))); }

Target:
public void testLongFixedSizeRangeFieldPartitionerRangePredicate() { final FieldPartitioner<Long, Long> fp = new LongFixedSizeRangeFieldPartitioner("num", 5); Assert.assertEquals(Ranges.closed(-5L, 10L), fp.project(Ranges.open(-2L, 15L))); Assert.assertEquals(Ranges.closed(5L, 10L), fp.project(Ranges.open(5L, 15L))); Assert.assertEquals(Ranges.closed(5L, 10L), fp.project(Ranges.open(4L, 15L))); Assert.assertEquals(Ranges.closed(0L, 15L), fp.project(Ranges.closed(4L, 15L))); Assert.assertEquals(Ranges.closed(5L, 20L), fp.project(Ranges.openClosed(5L, 21L))); Assert.assertEquals(Ranges.atMost(15L), fp.project(Ranges.atMost(15L))); Assert.assertEquals(Ranges.atMost(20L), fp.project(Ranges.lessThan(21L))); Assert.assertEquals(Ranges.atLeast(10L), fp.project(Ranges.atLeast(14L))); Assert.assertEquals(Ranges.singleton(10L), fp.projectStrict(Ranges.open(5L, 15L))); Assert.assertNull(fp.projectStrict(Ranges.open(5L, 14L))); Assert.assertEquals(Ranges.atMost(10L), fp.projectStrict(Ranges.atMost(15L))); Assert.assertEquals(Ranges.atMost(15L), fp.projectStrict(Ranges.lessThan(21L))); Assert.assertEquals(Ranges.atLeast(15L), fp.projectStrict(Ranges.atLeast(14L))); }
Source:
private String getTestSuiteNameToExecute(TestEnvironmentEntity testEnv) { List<String> testSuitesNames = testEnv.getTestSuites().stream().map(TestSuiteEntity::getTestSuiteId).collect(toList()); return jobExecutionService.readAll().stream() .map(JobExecutionEntity::getJob) .filter(job -> job.getEnvId().equals(testEnv.getEnvironmentId())) .map(JobEntity::getTestSuiteId) .filter(testSuitesNames::contains) .findFirst() .orElse(null); }

Target:
private Optional<String> getTestSuiteNameToExecute(TestEnvironmentEntity testEnv) { List<String> testSuitesNames = testEnv.getTestSuites().stream().map(TestSuiteEntity::getTestSuiteId).collect(toList()); return jobExecutionService.readAllPending().stream() .map(JobExecutionEntity::getJob) .filter(job -> job.getEnvId().equals(testEnv.getEnvironmentId())) .map(JobEntity::getTestSuiteId) .filter(testSuitesNames::contains) .findFirst(); }
Source:
public void throw_UnauthorizedException_if_not_logged_in() throws Exception { expectedException.expect(UnauthorizedException.class); actionTester.newRequest().setMethod("POST").execute(); }

Target:
public void throw_UnauthorizedException_if_not_logged_in() throws Exception { expectedException.expect(UnauthorizedException.class); ws.newRequest().setMethod("POST").execute(); }
Source:
public static Value sin( AnyValue in ) { if ( in == NO_VALUE ) { return NO_VALUE; } else if ( in instanceof NumberValue ) { return doubleValue( Math.sin( ((NumberValue) in).doubleValue() ) ); } else { throw new CypherTypeException( "sin requires numbers", null ); } }

Target:
public static Value sin( AnyValue in ) { if ( in == NO_VALUE ) { return NO_VALUE; } else if ( in instanceof NumberValue ) { return doubleValue( Math.sin( ((NumberValue) in).doubleValue() ) ); } else { throw needsNumbers( "sin()" ); } }
Source:
public ClassRequest(Class<?> testClass, boolean canUseSuiteMethod) { fRunner = new AllDefaultPossibilitiesBuilder(canUseSuiteMethod).safeRunnerForClass(testClass); }

Target:
public ClassRequest(Class<?> testClass, boolean canUseSuiteMethod) { fTestClass = testClass; fCanUseSuiteMethod = canUseSuiteMethod; }
Source:
private String generateRandomUniqueWord(int maxLength, boolean randomLength) { String singleByteChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String multiByteChars = "ÅÄÇÉÑÖÕÜàäâáãçëèêéîïìíñôöòóüûùúÿ"; StringBuilder data = new StringBuilder(); int byteLength = maxLength; if (randomLength && maxLength - 1 > 0) { byteLength = random.nextInt(maxLength - 1) + 1; } for (int i = byteLength; i > 0; i--) { if (i == 1) { data.append(singleByteChars.charAt(random.nextInt(singleByteChars.length() - 1))); } else { data.append(multiByteChars.charAt(random.nextInt(multiByteChars.length() - 1))); } } return data.toString(); }

Target:
private String generateRandomUniqueWord(int maxLength, boolean randomLength) { String singleByteChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String multiByteChars = "ÅÄÇÉÑÖÕÜàäâáãçëèêéîïìíñôöòóüûùúÿ"; StringBuilder data = new StringBuilder(); int wordLength = maxLength; if (randomLength && maxLength - 1 > 0) { wordLength = random.nextInt(maxLength - 1) + 1; } for (int i = wordLength; i > 0; i--) { if (random.nextBoolean()) { data.append(multiByteChars.charAt(random.nextInt(multiByteChars.length() - 1))); } else { data.append(singleByteChars.charAt(random.nextInt(singleByteChars.length() - 1))); } } return data.toString(); }