auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private SolrQuery getRealTimeQuery(SolrQuery originalQuery, Collection<String> ids) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("originalQuery: {}", getQueryParams(originalQuery)); } SolrQuery realTimeQuery = new SolrQuery(); for (Map.Entry<String, String[]> entry : originalQuery.getMap().entrySet()) { if (entry.getKey().equals(CommonParams.Q)) { realTimeQuery.set(CommonParams.FQ, entry.getValue()); } else { realTimeQuery.set(entry.getKey(), entry.getValue()); } } realTimeQuery.set(CommonParams.QT, GET_QUERY_HANDLER); realTimeQuery.set(IDS_KEY, ids.toArray(new String[ids.size()])); if (LOGGER.isDebugEnabled()) { LOGGER.debug("realTimeQuery: {}", getQueryParams(realTimeQuery)); } return realTimeQuery; }

Target:
private SolrQuery getRealTimeQuery(SolrQuery originalQuery, Collection<String> ids) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("originalQuery: {}", getQueryParams(originalQuery)); } SolrQuery realTimeQuery = new SolrQuery(); for (Map.Entry<String, String[]> entry : originalQuery.getMap().entrySet()) { if (CommonParams.Q.equals(entry.getKey())) { realTimeQuery.set(CommonParams.FQ, entry.getValue()); } else { realTimeQuery.set(entry.getKey(), entry.getValue()); } } realTimeQuery.set(CommonParams.QT, GET_QUERY_HANDLER); realTimeQuery.set(IDS_KEY, ids.toArray(new String[ids.size()])); if (LOGGER.isDebugEnabled()) { LOGGER.debug("realTimeQuery: {}", getQueryParams(realTimeQuery)); } return realTimeQuery; }
Source:
public void deleteCommand(@ApiParam("The id of the workspace") @PathParam("id") String id, @ApiParam("The name of the command to remove") @PathParam("name") String commandName) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException { final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); if (workspace.getConfig().getCommands().removeIf(command -> command.getName().equals(commandName))) { workspaceManager.updateWorkspace(id, workspace); } else { throw new NotFoundException(String.format("Command with name '%s' was not found in workspace with id %s", commandName, id)); } }

Target:
public void deleteCommand(@ApiParam("The id of the workspace") @PathParam("id") String id, @ApiParam("The name of the command to remove") @PathParam("name") String commandName) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException { final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); if (workspace.getConfig().getCommands().removeIf(command -> command.getName().equals(commandName))) { workspaceManager.updateWorkspace(id, workspace); } else { throw new NotFoundException( String.format("Command with name '%s' was not found in workspace '%s'", commandName, workspace.getConfig().getName())); } }
Source:
protected void loadConfig() { Comparator<ConfigProviderFactory> comparator = (f1, f2) -> { boolean b1 = f1.isFallback(); boolean b2 = f2.isFallback(); return b1 ^ b2 ? (b2 ? -1 : 1) : 0; }; ServiceLoader<ConfigProviderFactory> loader = ServiceLoader.load(ConfigProviderFactory.class, KeycloakApplication.class.getClassLoader()); Optional<Config.ConfigProvider> provider = StreamSupport.stream(loader.spliterator(), false) .sorted(comparator) .peek(p -> logger.infov("Trying ConfigProvider: {0}", p.getClass().getName())) .map(ConfigProviderFactory::create) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); Config.init(provider.orElseThrow(() -> new RuntimeException("No valid ConfigProvider(s) found"))); }

Target:
protected void loadConfig() { ServiceLoader<ConfigProviderFactory> loader = ServiceLoader.load(ConfigProviderFactory.class, KeycloakApplication.class.getClassLoader()); try { ConfigProviderFactory factory = loader.iterator().next(); logger.infov("Using ConfigProvider: {0}", factory.getClass().getName()); Config.init(factory.create().orElseThrow(() -> new RuntimeException("Failed to load Keycloak configuration"))); } catch (NoSuchElementException e) { throw new RuntimeException("No valid ConfigProvider found"); } }
Source:
private void readVal(Field f, Object o, DataInputStream in) throws DeserializationException, IOException, IllegalAccessException { synchronized (fieldOrderings) { Persisting p = f.getAnnotation(Persisting.class); Class type = f.getType(); try { f.setAccessible(true); if (type.equals(String.class)) { String read = ExtUtil.readString(in); f.set(o, p.nullable() ? ExtUtil.nullIfEmpty(read) : read); return; } else if (type.equals(Integer.TYPE)) { f.setInt(o, ExtUtil.readInt(in)); return; } else if (type.equals(Date.class)) { f.set(o, ExtUtil.readDate(in)); return; } else if (type.isArray()) { if (type.getComponentType().equals(Byte.TYPE)) { f.set(o, ExtUtil.readBytes(in)); return; } } else if (type.equals(Boolean.TYPE)) { f.setBoolean(o, ExtUtil.readBool(in)); return; } } finally { f.setAccessible(false); } throw new DeserializationException("Couldn't read persisted type " + f.getType().toString()); } }

Target:
private void readVal(Field f, Object o, DataInputStream in) throws DeserializationException, IOException, IllegalAccessException { synchronized (f) { Persisting p = f.getAnnotation(Persisting.class); Class type = f.getType(); try { f.setAccessible(true); if (type.equals(String.class)) { String read = ExtUtil.readString(in); f.set(o, p.nullable() ? ExtUtil.nullIfEmpty(read) : read); return; } else if (type.equals(Integer.TYPE)) { f.setInt(o, ExtUtil.readInt(in)); return; } else if (type.equals(Date.class)) { f.set(o, ExtUtil.readDate(in)); return; } else if (type.isArray()) { if (type.getComponentType().equals(Byte.TYPE)) { f.set(o, ExtUtil.readBytes(in)); return; } } else if (type.equals(Boolean.TYPE)) { f.setBoolean(o, ExtUtil.readBool(in)); return; } } finally { f.setAccessible(false); } throw new DeserializationException("Couldn't read persisted type " + f.getType().toString()); } }
Source:
public void fetchAvailableEngines(List<CategoryDTO> categoryDTOS, Consumer<List<EngineCategoryDTO>> callback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); List<EngineCategoryDTO> engines = Collections.synchronizedList(new ArrayList<>()); for (CategoryDTO categoryDTO : categoryDTOS) { final String engineName = categoryDTO.getName(); interactiveScriptSession.eval("include([\"Engines\", \"" + engineName + "\", \"Engine\", \"Object\"]);", ignored -> interactiveScriptSession.eval("new " + engineName + "().getAvailableVersions()", output -> { final EngineCategoryDTO engineCategoryDTO = new EngineCategoryDTO.Builder() .withName(engineName) .withDescription(engineName) .withSubCategories(unSerialize(output)) .build(); engines.add(engineCategoryDTO); }, this::throwError), this::throwError); } callback.accept(engines); }

Target:
public void fetchAvailableEngines(List<CategoryDTO> categoryDTOS, Consumer<List<EngineCategoryDTO>> callback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); StringBuilder includesBuilder = new StringBuilder(); StringBuilder constructorsBuilder = new StringBuilder(); constructorsBuilder.append("function fetchEngines() {\n"); constructorsBuilder.append("var engines = [];\n"); for (CategoryDTO categoryDTO : categoryDTOS) { final String engineName = categoryDTO.getName(); includesBuilder.append("include([\"Engines\", \"" + engineName + "\", \"Engine\", \"Object\"]);\n"); constructorsBuilder .append("engines[\"" + engineName + "\"] = new " + engineName + "().getAvailableVersions();\n"); } constructorsBuilder.append("return engines;\n"); constructorsBuilder.append("}\n"); constructorsBuilder.append("fetchEngines();"); interactiveScriptSession.eval(includesBuilder.toString(), ignored -> interactiveScriptSession.eval(constructorsBuilder.toString(), output -> { List<EngineCategoryDTO> engines = new ArrayList<>(); for (Map.Entry<String, Object> entry : ((Map<String, Object>) output).entrySet()) { final EngineCategoryDTO engineCategoryDTO = new EngineCategoryDTO.Builder() .withName(entry.getKey()) .withDescription(entry.getKey()) .withSubCategories(unSerialize(entry.getValue())) .build(); engines.add(engineCategoryDTO); } callback.accept(engines); }, this::throwError), this::throwError); }
Source:
public void complete() { abq.add(Optional.<T>empty()); }

Target:
public void complete() { completedLatch.assertOpen("Unexpected additional complete signal received!"); completedLatch.close(); abq.add(Optional.<T>empty()); }
Source:
private void initToolTips() { numberOfCoresTooltip.setText(constants.numOfCoresTooltipBasicDetails()); }

Target:
private void initToolTips() { numberOfCoresTooltip.setHtml(templates.numOfCoresTooltipBasicDetails()); }
Source:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter) { ListenerHolder listenerHolder = new ListenerHolder(listener, encoder, wrapper); Cache unwrapped = super.unwrapCache(this.cache); if(unwrapped instanceof CacheImpl) { ((CacheImpl)unwrapped).addListener(listenerHolder, filter, converter); } else { super.addListener(listener); } }

Target:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter) { ListenerHolder listenerHolder = new ListenerHolder(listener, keyEncoderClass, valueEncoderClass, keyWrapperClass, valueWrapperClass); Cache unwrapped = super.unwrapCache(this.cache); if (unwrapped instanceof CacheImpl) { ((CacheImpl) unwrapped).addListener(listenerHolder, filter, converter); } else { super.addListener(listener); } }
Source:
private void authenticateWithSSO(HttpServletRequest req) throws ServletException { String headerAuthorization = req.getHeader(FiltersHelper.Constants.HEADER_AUTHORIZATION); HttpURLConnection connection = null; try { connection = create(new URL("<LINK_0>")); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty(FiltersHelper.Constants.HEADER_AUTHORIZATION, headerAuthorization); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(headerAuthorization.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); ByteArrayOutputStream os = new ByteArrayOutputStream(); copy(connection.getInputStream(), os); connection.connect(); createUserSession(req, new String(os.toByteArray(), "UTF-8")); } catch (Exception e) { log.error("Exception obtaining ticket from sso", e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }

Target:
private void authenticateWithSSO(HttpServletRequest req) throws ServletException { String headerAuthorization = req.getHeader(FiltersHelper.Constants.HEADER_AUTHORIZATION); HttpURLConnection connection = null; try { connection = create(new URL("http://localhost/ovirt-engine/sso/login-credentials")); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty(FiltersHelper.Constants.HEADER_AUTHORIZATION, headerAuthorization); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Language", "en-US"); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (InputStream input = connection.getInputStream()) { copy(input, os); } connection.connect(); createUserSession(req, new String(os.toByteArray(), "UTF-8")); } } catch (Exception e) { log.error("Exception obtaining ticket from sso", e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }
Source:
public List<MimeMessage> generateFeedbackSessionClosingEmails(FeedbackSessionAttributes session) throws MessagingException, IOException { List<StudentAttributes> students = new ArrayList<StudentAttributes>(); if (fsLogic.isFeedbackSessionForStudentsToAnswer(session)) { List<StudentAttributes> studentsForCourse = studentsLogic.getStudentsForCourse(session.getCourseId()); for (StudentAttributes student : studentsForCourse) { try { if (!fsLogic.isFeedbackSessionFullyCompletedByStudent(session.getFeedbackSessionName(), session.getCourseId(), student.email)) { students.add(student); } } catch (EntityDoesNotExistException e) { log.warning("Course " + session.getCourseId() + " does not exist or " + "session " + session.getFeedbackSessionName() + " does not exist"); break; } } } String template = EmailTemplates.USER_FEEDBACK_SESSION_CLOSING; CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); List<InstructorAttributes> instructors = instructorsLogic.getInstructorsForCourse(session.getCourseId()); List<MimeMessage> emails = generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_CLOSING.getSubject()); for (MimeMessage email : emails) { email.setContent(email.getContent().toString().replace("${status}", "is closing soon"), "text/html"); } return emails; }

Target:
public List<MimeMessage> generateFeedbackSessionClosingEmails(FeedbackSessionAttributes session) throws MessagingException, IOException { List<StudentAttributes> students = new ArrayList<StudentAttributes>(); if (fsLogic.isFeedbackSessionForStudentsToAnswer(session)) { List<StudentAttributes> studentsForCourse = studentsLogic.getStudentsForCourse(session.getCourseId()); for (StudentAttributes student : studentsForCourse) { try { if (!fsLogic.isFeedbackSessionFullyCompletedByStudent(session.getFeedbackSessionName(), session.getCourseId(), student.email)) { students.add(student); } } catch (EntityDoesNotExistException e) { log.severe("Course " + session.getCourseId() + " does not exist or " + "session " + session.getFeedbackSessionName() + " does not exist"); break; } } } String template = EmailTemplates.USER_FEEDBACK_SESSION_CLOSING; CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); List<InstructorAttributes> instructors = instructorsLogic.getInstructorsForCourse(session.getCourseId()); List<MimeMessage> emails = generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_CLOSING.getSubject()); for (MimeMessage email : emails) { email.setContent(email.getContent().toString().replace("${status}", "is closing soon"), "text/html"); } return emails; }
Source:
public Mono<Void> runAsync() { return blobContainerAsyncClient.listBlobs() .ignoreElements() .then(); }

Target:
public Mono<Void> runAsync() { return blobContainerAsyncClient.listBlobs() .then(); }
Source:
public ZkBucketDataAccessor(String zkAddr) { HelixZkClient zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddr)); zkClient.setZkSerializer(new DummySerializer()); _zkSerializer = new ZNRecordJacksonSerializer(); _zkBaseDataAccessor = new ZkBaseDataAccessor(zkClient); }

Target:
public ZkBucketDataAccessor(String zkAddr) { this(zkAddr, DEFAULT_BUCKET_SIZE, DEFAULT_NUM_VERSIONS); }
Source:
public void cleanup( @PathVariable("id") Set<Long> ids, @RequestParam(defaultValue = "CLEANUP", name="action") TaskExecutionControllerDeleteAction[] actions) { final Set<TaskExecutionControllerDeleteAction> actionsAsSet = new HashSet<>(Arrays.asList(actions)); final SortedSet<Long> nonExistingTaskExecutions = new TreeSet<>(); for (Long id : ids) { final TaskExecution taskExecution = this.explorer.getTaskExecution(id); if (taskExecution == null) { nonExistingTaskExecutions.add(id); } } if (!nonExistingTaskExecutions.isEmpty()) { if (nonExistingTaskExecutions.size() == 1) { throw new NoSuchTaskExecutionException(nonExistingTaskExecutions.first()); } else { throw new NoSuchTaskExecutionException(nonExistingTaskExecutions); } } if (actionsAsSet.contains(TaskExecutionControllerDeleteAction.CLEANUP)) { for (Long id : ids) { this.taskDeleteService.cleanupExecution(id); } } if (actionsAsSet.contains(TaskExecutionControllerDeleteAction.REMOVE_DATA)) { this.taskDeleteService.deleteOneOrMoreTaskExecutions(ids); } }

Target:
public void cleanup( @PathVariable("id") Set<Long> ids, @RequestParam(defaultValue = "CLEANUP", name="action") TaskExecutionControllerDeleteAction[] actions) { final Set<TaskExecutionControllerDeleteAction> actionsAsSet = new HashSet<>(Arrays.asList(actions)); this.taskDeleteService.cleanupExecutions(actionsAsSet, ids); }
Source:
public Classpath getProviderClasspath() throws ArtifactResolutionException, ArtifactNotFoundException { final Map<String, Artifact> pluginArtifactMap = getPluginArtifactMap(); Class<?> c = AbstractSurefireMojo.this.getClass(); Artifact plugin; if ( c.getName().equals( "org.apache.maven.plugin.failsafe.IntegrationTestMojo" ) ) { plugin = pluginArtifactMap.get( "org.apache.maven.plugins:maven-failsafe-plugin" ); } else { plugin = pluginArtifactMap.get( "org.apache.maven.plugins:maven-surefire-plugin" ); } return dependencyResolver.addProviderToClasspath( pluginArtifactMap, plugin ); }

Target:
public Classpath getProviderClasspath() throws ArtifactResolutionException, ArtifactNotFoundException { return dependencyResolver.addProviderToClasspath( pluginArtifactMap, getMojoArtifact() ); }
Source:
private boolean canCreateContainerInTarget() { boolean containerCanBeCreateInTarget = false; if (nodeContainer != null) { containerCanBeCreateInTarget = permissionAuthority.canEditInstance(nodeContainer) && nodeContainer.getTarget() != null && !nodeContainer.getTarget().eIsProxy(); } else { if (diagram != null) { containerCanBeCreateInTarget = permissionAuthority.canEditInstance(diagram); if (containerCanBeCreateInTarget && diagram instanceof DSemanticDecorator) { containerCanBeCreateInTarget = ((DSemanticDecorator) diagram).getTarget() != null && !((DSemanticDecorator) diagram).getTarget().eIsProxy(); } } } return containerCanBeCreateInTarget; }

Target:
private boolean canCreateContainerInTarget() { boolean containerCanBeCreatedInTarget = false; if (nodeContainer != null) { containerCanBeCreatedInTarget = permissionAuthority.canEditInstance(nodeContainer); if (containerCanBeCreatedInTarget) { EObject target = nodeContainer.getTarget(); containerCanBeCreatedInTarget = target != null && !target.eIsProxy(); } } else if (diagram != null) { containerCanBeCreatedInTarget = permissionAuthority.canEditInstance(diagram); if (containerCanBeCreatedInTarget && diagram instanceof DSemanticDecorator) { EObject target = ((DSemanticDecorator) diagram).getTarget(); containerCanBeCreatedInTarget = target != null && !target.eIsProxy(); } } return containerCanBeCreatedInTarget; }
Source:
protected BlobAsyncClientBase(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) { this.azureBlobStorage = new AzureBlobStorageBuilder() .pipeline(pipeline) .url(url) .version(serviceVersion.getVersion()) .build(); this.serviceVersion = serviceVersion; this.accountName = accountName; this.containerName = containerName; this.blobName = blobName; this.snapshot = snapshot; this.customerProvidedKey = customerProvidedKey; this.blobPropertyHelper = null; BlobHelper.PropertyAccessor propertyAccessor = new BlobHelper.PropertyAccessor() { @Override public BlobHelper getHelper(final BlobAsyncClientBase client) { return client.blobPropertyHelper; } @Override public AzureBlobStorageImpl getAzureBlobStorageImpl(final BlobAsyncClientBase client) { return client.azureBlobStorage; } @Override public CpkInfo getCustomerProvidedKey(final BlobAsyncClientBase client) { return client.customerProvidedKey; } }; BlobHelper.setPropertyAccessor(propertyAccessor); }

Target:
protected BlobAsyncClientBase(HttpPipeline pipeline, String url, BlobServiceVersion serviceVersion, String accountName, String containerName, String blobName, String snapshot, CpkInfo customerProvidedKey) { this.azureBlobStorage = new AzureBlobStorageBuilder() .pipeline(pipeline) .url(url) .version(serviceVersion.getVersion()) .build(); this.serviceVersion = serviceVersion; this.accountName = accountName; this.containerName = containerName; this.blobName = blobName; this.snapshot = snapshot; this.customerProvidedKey = customerProvidedKey; BlobHelper.setAsyncPropertyAccessor(new BlobPropertyAccessor()); }
Source:
public AddDistributedCache(Builder builder) { super(builder, CacheType.DISTRIBUTED_CACHE); this.asyncMarshalling = builder.asyncMarshalling; this.mode = builder.mode; this.queueFlushInterval = builder.queueFlushInterval; this.remoteTimeout = builder.remoteTimeout; this.capacityFactor = builder.capacityFactor; this.consistentHashStrategy = builder.consistentHashStrategy; this.l1lifespan = builder.l1lifespan; this.owners = builder.owners; this.segments = builder.segments; }

Target:
private AddDistributedCache(Builder builder) { super(builder, CacheType.DISTRIBUTED_CACHE); this.asyncMarshalling = builder.asyncMarshalling; this.mode = builder.mode; this.queueFlushInterval = builder.queueFlushInterval; this.remoteTimeout = builder.remoteTimeout; this.capacityFactor = builder.capacityFactor; this.consistentHashStrategy = builder.consistentHashStrategy; this.l1lifespan = builder.l1lifespan; this.owners = builder.owners; this.segments = builder.segments; }
Source:
private Timestamp toTimestamp(TimeMeta tm, TimeZone tz) { long javaTime = DateTimeUtil.julianTimeToJavaTime(DateTimeUtil.toJulianTimestamp(tm)); Instant instant = Instant.ofEpochMilli(javaTime); if (tz != null) { ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, tz.toZoneId()); return Timestamp.valueOf(zonedDateTime.toLocalDateTime()); } else { return Timestamp.from(instant); } }

Target:
private Timestamp toTimestamp(TimeMeta tm, TimeZone tz) { return DateTimeUtil.toJavaTimestamp(tm, tz); }
Source:
public PaginationList build() { if (this.contents == null) { this.contents = ImmutableList.of(); } if (this.paginationList == null) { this.paginationList = new SpongePaginationList(this.service, this.contents, this.title, this.header, this.footer, this.paginationSpacer, this.linesPerPage); } return this.paginationList; }

Target:
public PaginationList build() { checkState(this.contents != null, "The contents of the pagination list cannot be null!"); if (this.paginationList == null) { this.paginationList = new SpongePaginationList(this.service, this.contents, this.title, this.header, this.footer, this.paginationSpacer, this.linesPerPage); } return this.paginationList; }
Source:
public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { service.findCashPoints(Context.getLocationService().getLocation(1),"Test 1 Cash Point",false); }

Target:
public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { service.findCashPoints(Context.getLocationService().getLocation(1),"",false); }
Source:
public void testFullResolveHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin1", 0), new PutOperation<>(1L, "Albin2", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin3", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Map<Long, PutOperation<Long, String>> resolved = resolver.resolveChain(chain, 3); assertThat(resolved, hasEntry(1L, new PutOperation<>(1L, "Albin3", 3))); }

Target:
public void testFullResolveHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin", 0), new PutOperation<>(1L, "Albin", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Map<Long, PutOperation<Long, String>> resolved = resolver.resolveChain(chain, 3); assertThat(resolved, hasEntry(1L, new PutOperation<>(1L, "Albin", 3))); }
Source:
protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { super(); this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; }

Target:
protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; }
Source:
public QueryResponse getStudy(@PathVariable("study") String study, @RequestParam(name = "species") String species, HttpServletResponse response) throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); VariantStudySummary variantStudySummary = variantStudySummaryRepository.findByStudyNameOrStudyId(study); QueryResult<VariantStudySummary> queryResult = new QueryResult<>(); if (variantStudySummary == null) { queryResult = Utils.buildQueryResult(Collections.emptyList()); queryResult.setErrorMsg("Study identifier not found"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { queryResult = Utils.buildQueryResult(Collections.singletonList(variantStudySummary)); } return setQueryResponse(queryResult); }

Target:
public QueryResponse getStudy(@PathVariable("study") String study, @RequestParam(name = "species") String species, HttpServletResponse response) throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); VariantStudySummary variantStudySummary = variantStudySummaryRepository.findByStudyNameOrStudyId(study); QueryResult<VariantStudySummary> queryResult; if (variantStudySummary == null) { queryResult = Utils.buildQueryResult(Collections.emptyList()); queryResult.setErrorMsg("Study identifier not found"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { queryResult = Utils.buildQueryResult(Collections.singletonList(variantStudySummary)); } return setQueryResponse(queryResult); }
Source:
private void changeAvatar(final File selectedFile, final Component parent) { SwingWorker worker = new SwingWorker() { public Object construct() { try { ImageIcon imageOnDisk = new ImageIcon(selectedFile.getCanonicalPath()); setAvatar(imageOnDisk); return cropImageFile(selectedFile); } catch (IOException ex) { Log.error(ex); } return null; } public void finished() { File avatarImage = (File)get(); avatarFile = avatarImage; } }; worker.start(); }

Target:
private void changeAvatar(final File selectedFile, final Component parent) { SwingWorker worker = new SwingWorker() { public Object construct() { return cropImageFile(selectedFile); } public void finished() { BufferedImage avatarImage = (BufferedImage)get(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(avatarImage, "png", baos); setAvatar(new ImageIcon(avatarImage)); setAvatarBytes(baos.toByteArray()); } catch (IOException ex) { Log.error(ex); } } }; worker.start(); }
Source:
private URL appendQuery(String query, URL baseURL) { try { URI baseURI = baseURL.toURI(); String baseQuery = baseURI.getQuery(); if (baseQuery == null || baseQuery.isEmpty()) { baseQuery = query; } else { if (query != null && !query.isEmpty()) { baseQuery = baseQuery + "&" + query; } } if (baseQuery.isEmpty()) { baseQuery = null; } URL url = new URI(baseURI.getScheme(), baseURI.getUserInfo(), baseURI.getHost(), baseURI.getPort(), baseURI.getPath(), baseQuery, baseURI.getFragment()).toURL(); String temp[] = url.toString().split("\\?"); temp[0] = temp[0].replace("%252F", "%2F"); String urlString = temp[0]; if(temp.length > 1){ urlString = urlString + "?" + temp[1]; } return new URL(urlString); } catch (MalformedURLException ex) { Log.e(TAG, "The URL could not be created from " + baseURL.toString(), ex); throw new RuntimeException(ex); } catch (URISyntaxException ex) { Log.e(TAG, "Error turning " + query + " into URI query.", ex); throw new RuntimeException(ex); } }

Target:
private URL appendQuery(String query, URL baseURL) { try { Uri uri = Uri.parse(baseURL.toString()); String baseQuery = uri.getEncodedQuery(); if (baseQuery == null || baseQuery.isEmpty()) { baseQuery = query; } else { if (query != null && !query.isEmpty()) { baseQuery = baseQuery + "&" + query; } } if (baseQuery.isEmpty()) { baseQuery = null; } Uri.Builder uriBuilder = uri.buildUpon(); uriBuilder.encodedQuery(baseQuery); return new URL(uriBuilder.build().toString()); } catch (MalformedURLException ex) { Log.e(TAG, "The URL could not be created from " + baseURL.toString(), ex); throw new RuntimeException(ex); } }
Source:
public void testLongPathWithoutCloneOption() throws Exception { RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange('a', 'z').build(); String fileName = generator.generate(200); File tempDir = Files.createTempDirectory(fileName).toFile(); if (isWindows()) { GitException gitException = assertThrows(GitException.class, () -> { if (workspace.getGitFileDir().renameTo(tempDir)) { CloneCommand cmd = workspace.getGitClient().clone_().url(workspace.localMirror()).repositoryName("origin"); cmd.execute(); } }); assertThat(gitException.getMessage().contains("FileName too long"), is(true)); } }

Target:
public void testLongPathWithoutCloneOption() throws Exception { RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange('a', 'z').build(); String fileName = generator.generate(133); String subDirName = generator.generate(80); File tempDir = Files.createTempDirectory(fileName).toFile(); File tempSubDir = new File(tempDir, subDirName); Path subDirectory = Paths.get(tempSubDir.getAbsolutePath()); Files.createDirectories(subDirectory); assertThat(tempSubDir.getAbsolutePath().length(), greaterThan(259)); if (Files.isDirectory(subDirectory)) { File[] files = subDirectory.toFile().listFiles(); } if (Files.isDirectory(subDirectory)) { WorkspaceWithRepo tempRepo = new WorkspaceWithRepo(tempSubDir, gitImplName, listener); if (isWindows()) { GitException gitException = assertThrows(GitException.class, () -> { CloneCommand cmd = tempRepo.getGitClient().clone_().url(tempRepo.localMirror()).repositoryName("origin"); cmd.execute(); }); assertThat(gitException.getMessage(), containsString("FileName too long")); } } }
Source:
private String getTypeOfPeopleCanViewComment(FeedbackResponseCommentAttributes comment, FeedbackQuestionAttributes relatedQuestion) { List<FeedbackParticipantType> showCommentTo; if (comment.isVisibilityFollowingFeedbackQuestion) { showCommentTo = relatedQuestion.showResponsesTo; } else { showCommentTo = comment.showCommentTo; } if (showCommentTo == null || showCommentTo.isEmpty()) { return "nobody"; } StringBuilder peopleCanView = new StringBuilder(100); for (int i = 0; i < showCommentTo.size(); i++) { FeedbackParticipantType commentViewer = showCommentTo.get(i); if (i == showCommentTo.size() - 1 && showCommentTo.size() > 1) { peopleCanView.append("and "); } switch (commentViewer) { case GIVER: peopleCanView.append("response giver, "); break; case RECEIVER: peopleCanView.append("response recipient, "); break; case OWN_TEAM_MEMBERS: peopleCanView.append("response giver's team, "); break; case RECEIVER_TEAM_MEMBERS: peopleCanView.append("response recipient's team, "); break; case STUDENTS: peopleCanView.append("other students in this course, "); break; case INSTRUCTORS: peopleCanView.append("instructors, "); break; case OWN_TEAM_MEMBERS_INCLUDING_SELF: peopleCanView.append("response giver's team members and response giver, "); break; default: break; } } String peopleCanViewString = peopleCanView.toString(); return removeEndComma(peopleCanViewString); }

Target:
private String getTypeOfPeopleCanViewComment(FeedbackResponseCommentAttributes comment, FeedbackQuestionAttributes relatedQuestion) { List<FeedbackParticipantType> showCommentTo; if (comment.isVisibilityFollowingFeedbackQuestion) { showCommentTo = relatedQuestion.showResponsesTo; } else { showCommentTo = comment.showCommentTo; } if (showCommentTo == null || showCommentTo.isEmpty()) { return "nobody"; } StringBuilder peopleCanView = new StringBuilder(100); for (int i = 0; i < showCommentTo.size(); i++) { FeedbackParticipantType commentViewer = showCommentTo.get(i); if (i == showCommentTo.size() - 1 && showCommentTo.size() > 1) { peopleCanView.append("and "); } switch (commentViewer) { case GIVER: peopleCanView.append("response giver, "); break; case RECEIVER: peopleCanView.append("response recipient, "); break; case OWN_TEAM_MEMBERS: peopleCanView.append("response giver's team members, "); break; case RECEIVER_TEAM_MEMBERS: peopleCanView.append("response recipient's team, "); break; case STUDENTS: peopleCanView.append("other students in this course, "); break; case INSTRUCTORS: peopleCanView.append("instructors, "); break; case OWN_TEAM_MEMBERS_INCLUDING_SELF: peopleCanView.append("response giver's team members and response giver, "); break; default: break; } } String peopleCanViewString = peopleCanView.toString(); return removeEndComma(peopleCanViewString); }
Source:
public synchronized void performFailover(T currentProxy) { RPC.stopProxy(currentProxy); Set<String> rmIds = new HashSet<>(); for (Entry<String, T> entry : proxies.entrySet()) { if (entry.getValue().equals(currentProxy)) { rmIds.add(entry.getKey()); } } for (String rmId : rmIds) { proxies.remove(rmId); } super.performFailover(currentProxy); }

Target:
public synchronized void performFailover(T currentProxy) { RPC.stopProxy(currentProxy); Set<String> rmIds = new HashSet<>(); for (Entry<String, T> entry : proxies.entrySet()) { T proxy = entry.getValue(); if (proxy.equals(currentProxy)) { String rmId = entry.getKey(); rmIds.add(rmId); } } for (String rmId : rmIds) { proxies.remove(rmId); } super.performFailover(currentProxy); }
Source:
public void stop() { LOG.info("Stopping event hub system consumer..."); reconnectTaskRunner.shutdown(); shutdownEventHubsManagers(); isStarted = false; LOG.info("Event hub system consumer stopped."); }

Target:
public void stop() { LOG.info("Stopping event hub system consumer..."); try { reconnectTaskRunner.shutdown(); shutdownEventHubsManagers(); isStarted = false; } catch (Exception e) { LOG.warn("Exception during stop.", e); } LOG.info("Event hub system consumer stopped."); }
Source:
protected void onCreate(Bundle savedInstanceState) { ((WordPress) getApplication()).component().inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); if (savedInstanceState == null) { if (getIntent() != null) { mJetpackConnectSource = (JetpackConnectionSource) getIntent().getSerializableExtra(ARG_JETPACK_CONNECT_SOURCE); } mLoginAnalyticsListener.trackLoginAccessed(); switch (getLoginMode()) { case FULL: case WPCOM_LOGIN_ONLY: showFragment(new LoginPrologueFragment(), LoginPrologueFragment.TAG); break; case SELFHOSTED_ONLY: showFragment(new LoginSiteAddressFragment(), LoginSiteAddressFragment.TAG); break; case JETPACK_STATS: case WPCOM_LOGIN_DEEPLINK: case WPCOM_REAUTHENTICATE: case SHARE_INTENT: checkSmartLockPasswordAndStartLogin(); break; } } else { mSignupSheetDisplayed = savedInstanceState.getBoolean(KEY_SIGNUP_SHEET_DISPLAYED); mSmartLockHelperState = SmartLockHelperState.valueOf( savedInstanceState.getString(KEY_SMARTLOCK_HELPER_STATE)); if (mSmartLockHelperState != SmartLockHelperState.NOT_TRIGGERED) { initSmartLockHelperConnection(); } if (mSignupSheetDisplayed) { mSignupSheet = new SignupBottomSheetDialogFragment(this); mSignupSheet.show(getSupportFragmentManager(), SignupBottomSheetDialogFragment.TAG); } } }

Target:
protected void onCreate(Bundle savedInstanceState) { ((WordPress) getApplication()).component().inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); if (savedInstanceState == null) { if (getIntent() != null) { mJetpackConnectSource = (JetpackConnectionSource) getIntent().getSerializableExtra(ARG_JETPACK_CONNECT_SOURCE); } mLoginAnalyticsListener.trackLoginAccessed(); switch (getLoginMode()) { case FULL: case WPCOM_LOGIN_ONLY: showFragment(new LoginPrologueFragment(), LoginPrologueFragment.TAG); break; case SELFHOSTED_ONLY: showFragment(new LoginSiteAddressFragment(), LoginSiteAddressFragment.TAG); break; case JETPACK_STATS: case WPCOM_LOGIN_DEEPLINK: case WPCOM_REAUTHENTICATE: case SHARE_INTENT: checkSmartLockPasswordAndStartLogin(); break; } } else { mSmartLockHelperState = SmartLockHelperState.valueOf( savedInstanceState.getString(KEY_SMARTLOCK_HELPER_STATE)); if (mSmartLockHelperState != SmartLockHelperState.NOT_TRIGGERED) { initSmartLockHelperConnection(); } } }
Source:
protected Event createEventByType(String eventType, String topic, String payload, String source) throws Exception { if (topic.endsWith("/failed")) { String[] properties = deserializePayload(payload, String[].class); Event event = new ExtensionEvent(topic, payload, properties[0], properties[1]); return event; } else { String id = deserializePayload(payload, String.class); Event event = new ExtensionEvent(topic, payload, id); return event; } }

Target:
protected Event createEventByType(String eventType, String topic, String payload, String source) throws Exception { if (topic.endsWith(EXTENSION_FAILURE_EVENT_TOPIC_POSTFIX)) { String[] properties = deserializePayload(payload, String[].class); Event event = new ExtensionEvent(topic, payload, properties[0], properties[1]); return event; } else { String id = deserializePayload(payload, String.class); Event event = new ExtensionEvent(topic, payload, id); return event; } }
Source:
public void reportSingleLogMessage( String logger, Level loglevel, String message, String exception ) { if( Backendless.isCodeRunner() ) { Invoker.invokeSync( LOGGING_SERVER_ALIAS, "log", new Object[]{ Backendless.getApplicationId(), Backendless.getVersion(), loglevel.name(), logger, message, exception } ); } else { Invoker.invokeAsync( LOGGING_SERVER_ALIAS, "log", new Object[]{ Backendless.getApplicationId(), Backendless.getVersion(), loglevel.name(), logger, message, exception }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } }

Target:
public void reportSingleLogMessage( String logger, Level loglevel, String message, String exception ) { if( Backendless.isCodeRunner() ) { Invoker.invokeSync( LOGGING_SERVER_ALIAS, "log", new Object[]{ loglevel.name(), logger, message, exception } ); } else { Invoker.invokeAsync( LOGGING_SERVER_ALIAS, "log", new Object[]{ loglevel.name(), logger, message, exception }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } }
Source:
public void createWithResponse() { DirectoryClient directoryClient = createClientWithSASToken(); Response<DirectoryInfo> response = directoryClient.createWithResponse( Collections.singletonMap("directory", "metadata"), Duration.ofSeconds(1), new Context(key1, value1)); System.out.println("Completed creating the directory with status code: " + response.statusCode()); END: com.azure.storage.file.directoryClient.createWithResponse#map-duration-context }

Target:
public void createWithResponse() { DirectoryClient directoryClient = createClientWithSASToken(); FileSmbProperties smbProperties = new FileSmbProperties(); String filePermission = "filePermission"; Response<DirectoryInfo> response = directoryClient.createWithResponse(smbProperties, filePermission, Collections.singletonMap("directory", "metadata"), Duration.ofSeconds(1), new Context(key1, value1)); System.out.println("Completed creating the directory with status code: " + response.statusCode()); END: com.azure.storage.file.directoryClient.createWithResponse#filesmbproperties-string-map-duration-context }
Source:
public void execute() { CustomizeEntryTypeDialogView dialog = new CustomizeEntryTypeDialogView(this.frame.getCurrentBasePanel().getBibDatabaseContext()); dialog.showAndWait(); }

Target:
public void execute() { BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null")); CustomizeEntryTypeDialogView dialog = new CustomizeEntryTypeDialogView(database, entryTypesManager); dialog.showAndWait(); }
Source:
public void testSegmentedResponseTransmit() { if (PropertyUtil.getFirstApiLevel() < 28) { return; } try { waitForConnection(); Reader[] readers = seService.getReaders(); for (Reader reader : readers) { for (byte[] apdu : SEGMENTED_RESP_APDU) { byte[] response = internalTransmitApdu(reader, apdu); byte[] b = { 0x00, 0x00, apdu[2], apdu[3] }; ByteBuffer wrapped = ByteBuffer.wrap(b); int expectedLength = wrapped.getInt(); assertEquals(response.length, expectedLength + 2); assertEquals(response[response.length - 1] & 0xFF, 0x00); assertEquals(response[response.length - 2] & 0xFF, 0x90); assertEquals(response[response.length - 3] & 0xFF, 0xFF); } } } catch (Exception e) { fail("unexpected exception " + e); } }

Target:
public void testSegmentedResponseTransmit() { if (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.P) { return; } try { waitForConnection(); Reader[] readers = seService.getReaders(); for (Reader reader : readers) { for (byte[] apdu : SEGMENTED_RESP_APDU) { byte[] response = internalTransmitApdu(reader, apdu); byte[] b = { 0x00, 0x00, apdu[2], apdu[3] }; ByteBuffer wrapped = ByteBuffer.wrap(b); int expectedLength = wrapped.getInt(); assertEquals(response.length, expectedLength + 2); assertEquals(response[response.length - 1] & 0xFF, 0x00); assertEquals(response[response.length - 2] & 0xFF, 0x90); assertEquals(response[response.length - 3] & 0xFF, 0xFF); } } } catch (Exception e) { fail("unexpected exception " + e); } }
Source:
public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } int totDuration = 0; int totMotion = 0; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += stat.motionScore.numMotions; totDuration += stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentageFloat = (float) totMotion / (float) totDuration; final int averageMotionPercentage = (int) (averageMotionPercentageFloat * 100.0f); final float overallDiffFloat = (averageMotionPercentageFloat - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC * 100.0f; final int overallDiff = (int) overallDiffFloat; Text text; if (Math.abs(overallDiffFloat) >= SIGNIFICANT_DIFF) { if (overallDiffFloat > 0) { text = SleepMotionMsgEN.moreMovement(numDays, overallDiff, averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, overallDiff, averageMotionPercentage); } } else { text = SleepMotionMsgEN.equalMovement(numDays, overallDiff, averageMotionPercentage); } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }

Target:
public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } float totDuration = 0.0f; float totMotion = 0.0f; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += (float) stat.motionScore.numMotions; totDuration += (float) stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentage = ((totMotion / totDuration) * 100.0f); final float overallDiff = (( averageMotionPercentage - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC ) * 100.0f; Text text; if (Math.abs(overallDiff) >= SIGNIFICANT_DIFF) { if (overallDiff > 0) { text = SleepMotionMsgEN.moreMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } else { if ((int) overallDiff != 0) { text = SleepMotionMsgEN.equalMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.reallyEqualMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }
Source:
public void whenDeleteEventTypeNotAdminAndDeletionDeactivatedThenForbidden() throws Exception { final EventType eventType = buildDefaultEventType(); doReturn(eventType).when(eventTypeRepository).findByName(eventType.getName()); doReturn(Optional.of(eventType)).when(eventTypeRepository).findByNameO(eventType.getName()); doReturn(SecuritySettings.AuthMode.BASIC).when(settings).getAuthMode(); doReturn(true).when(featureToggleService).isFeatureEnabled(CHECK_APPLICATION_LEVEL_PERMISSIONS); doReturn(true).when(featureToggleService).isFeatureEnabled(DISABLE_EVENT_TYPE_DELETION); final Multimap<TopicRepository, String> topicsToDelete = ArrayListMultimap.create(); topicsToDelete.put(topicRepository, eventType.getTopic()); doReturn(topicsToDelete).when(timelineService).deleteAllTimelinesForEventType(eventType.getName()); deleteEventType(eventType.getName(), "somebody").andExpect(status().isForbidden()); }

Target:
public void whenDeleteEventTypeNotAdminAndDeletionDeactivatedThenForbidden() throws Exception { final EventType eventType = buildDefaultEventType(); postEventType(eventType); disableETDeletionFeature(); deleteEventType(eventType.getName(), "somebody").andExpect(status().isForbidden()); }
Source:
public void testDateTimeFormatterLocaleChange() throws AuthenticationException { DefaultTokenCacheStore store = (DefaultTokenCacheStore) setupItems(); List<TokenCacheItem> tokens = store.getTokensForResource("resource"); final long precision = 1000; TokenCacheItem item = tokens.get(0); String cacheKey = CacheKey.createCacheKey(item); Calendar time = Calendar.getInstance(); Date dateTimeNow = time.getTime(); long timeNowMiliSeconds = dateTimeNow.getTime(); item.setExpiresOn(dateTimeNow); store.setItem(cacheKey, item); TokenCacheItem fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.FRANCE); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.US); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+03:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+05:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); }

Target:
public void testDateTimeFormatterLocaleChange() throws AuthenticationException { final DefaultTokenCacheStore store = (DefaultTokenCacheStore) setupItems(); List<TokenCacheItem> tokens = store.getTokensForResource("resource"); final long precision = 1000; TokenCacheItem item = tokens.get(0); String cacheKey = CacheKey.createCacheKey(item); Calendar time = Calendar.getInstance(); Date dateTimeNow = time.getTime(); long timeNowMiliSeconds = dateTimeNow.getTime(); item.setExpiresOn(dateTimeNow); store.setItem(cacheKey, item); TokenCacheItem fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.FRANCE); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.US); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+03:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+05:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); }