auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) throws MDMAPIException { if (log.isDebugEnabled()) { log.debug("Sending enrollment invitation mail to existing user."); } DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); try { int i; for (i = 0; i < usernames.size(); i++) { EmailMessageProperties emailMessageProperties = new EmailMessageProperties(); emailMessageProperties .setFirstName(getClaimValue(usernames.get(i), Constants.USER_CLAIM_FIRST_NAME)); emailMessageProperties.setUserName(usernames.get(i)); String[] mailAddress = new String[1]; mailAddress[0] = getClaimValue(usernames.get(i), Constants.USER_CLAIM_EMAIL_ADDRESS); if (StringUtils.isNotEmpty(mailAddress[0])) { emailMessageProperties.setMailTo(mailAddress); deviceManagementProviderService.sendEnrolmentInvitation(emailMessageProperties); } } } catch (UserStoreException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } catch (DeviceManagementException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); }

Target:
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) throws MDMAPIException { if (log.isDebugEnabled()) { log.debug("Sending enrollment invitation mail to existing user."); } DeviceManagementProviderService deviceManagementProviderService = MDMAPIUtils.getDeviceManagementService(); try { for (int i = 0; i < usernames.size(); i++) { EmailMessageProperties emailMessageProperties = new EmailMessageProperties(); emailMessageProperties .setFirstName(getClaimValue(usernames.get(i), Constants.USER_CLAIM_FIRST_NAME)); emailMessageProperties.setUserName(usernames.get(i)); String[] mailAddress = new String[1]; mailAddress[0] = getClaimValue(usernames.get(i), Constants.USER_CLAIM_EMAIL_ADDRESS); if (StringUtils.isNotEmpty(mailAddress[0])) { emailMessageProperties.setMailTo(mailAddress); deviceManagementProviderService.sendEnrolmentInvitation(emailMessageProperties); } } } catch (UserStoreException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } catch (DeviceManagementException e) { String errorMsg = "Exception in trying to invite user."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } ResponsePayload responsePayload = new ResponsePayload(); responsePayload.setStatusCode(HttpStatus.SC_OK); responsePayload.setMessageFromServer("Email invitation was successfully sent to user."); return Response.status(HttpStatus.SC_OK).entity(responsePayload).build(); }
Source:
private void handleUnmanagedCommands() { List<AsyncTask> asyncTasks = asyncTaskDao.getAll(); Set<Guid> asyncTaskManagerManagedCommands = asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getRootCommandId()).collect(Collectors.toSet()); asyncTaskManagerManagedCommands.addAll(asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getCommandId()).collect(Collectors.toSet())); ENDED_WITH_FAILURE. getCommands(false).stream() .filter(x -> !x.isCallbackEnabled()) .filter(x -> x.getCommandStatus() == CommandStatus.ACTIVE) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> commandsCache.updateCommandStatus(x.getId(), CommandStatus.ENDED_WITH_FAILURE)); getCommands(false).stream() .filter(x -> x.getCommandStatus().isDuringExecution()) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> retrieveCommand(x.getId()).reacquireLocks()); }

Target:
private void handleUnmanagedCommands() { List<AsyncTask> asyncTasks = asyncTaskDao.getAll(); Set<Guid> asyncTaskManagerManagedCommands = asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getRootCommandId()).collect(Collectors.toSet()); asyncTaskManagerManagedCommands.addAll(asyncTasks.stream().filter(x -> x.getVdsmTaskId() != null) .map(x -> x.getCommandId()).collect(Collectors.toSet())); ENDED_WITH_FAILURE. getCommands(false).stream() .filter(x -> !x.isCallbackEnabled()) .filter(x -> x.getCommandStatus() == CommandStatus.ACTIVE) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> commandsCache.updateCommandStatus(x.getId(), CommandStatus.ENDED_WITH_FAILURE)); getCommands(false).stream() .filter(x -> x.isCallbackEnabled()) .filter(x -> x.getCommandStatus().isDuringExecution()) .filter(x -> !asyncTaskManagerManagedCommands.contains(x.getId())) .forEach(x -> retrieveCommand(x.getId()).reacquireLocks()); }
Source:
public void filter(final ContainerRequestContext requestContext) throws IOException { if (!denyAll) { if (scopesAllowed.length > 0 && requestContext.getSecurityContext().getUserPrincipal() == null) { throw new NotAuthorizedException(LocalizationMessages.USER_NOT_AUTHORIZED()); } for (final OAuthScope role : scopesAllowed) { if (requestContext.getSecurityContext().isUserInRole(role.toString())) { return; } } } LOGGER.warn("Access Token not authorized for any of the allowed scopes."); throw new ForbiddenException(); }

Target:
public void filter(final ContainerRequestContext requestContext) throws IOException { if (!denyAll) { if (scopesAllowed.length > 0 && requestContext.getSecurityContext().getUserPrincipal() == null) { throw new NotAuthorizedException(LocalizationMessages.USER_NOT_AUTHORIZED()); } for (final OAuthScope role : scopesAllowed) { if (requestContext.getSecurityContext().isUserInRole(role.toString())) { return; } } } final AccessToken token = (AccessToken) requestContext.getSecurityContext().getUserPrincipal(); LOGGER.warn("Token ({}) not authorized for any of the allowed scopes {}. Account ID: {}, App ID: {}", token.token, scopesAllowed, token.accountId, token.appId); throw new ForbiddenException(); }
Source:
public DynamicSchemaResolver(List<String> additionalFields) { this.tinyBinaryFunction = this::newTinyBinary; this.schemaFields = new SchemaFields(); metadataMaximumBytes = getMetadataSizeLimit(); anyTextFields = getAnyTextFields(); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED); fieldsCache.add( Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED + SchemaFields.HAS_CASE); fieldsCache.add(Metacard.TAGS + SchemaFields.TEXT_SUFFIX); Set<String> basicTextAttributes = MetacardImpl.BASIC_METACARD .getAttributeDescriptors() .stream() .filter(descriptor -> BasicTypes.STRING_TYPE.equals(descriptor.getType())) .map(stringDescriptor -> stringDescriptor.getName() + SchemaFields.TEXT_SUFFIX) .collect(Collectors.toSet()); fieldsCache.add(Validation.VALIDATION_ERRORS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Validation.VALIDATION_WARNINGS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(SchemaFields.METACARD_TYPE_FIELD_NAME); fieldsCache.add(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); for (String field : additionalFields) { if (StringUtils.isNotBlank(field)) { fieldsCache.add(field); } } }

Target:
public DynamicSchemaResolver(List<String> additionalFields) { this.tinyBinaryFunction = this::newTinyBinary; this.schemaFields = new SchemaFields(); metadataMaximumBytes = getMetadataSizeLimit(); anyTextFields = getAnyTextFields(); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED); fieldsCache.add( Metacard.ID + SchemaFields.TEXT_SUFFIX + SchemaFields.TOKENIZED + SchemaFields.HAS_CASE); fieldsCache.add(Metacard.TAGS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Validation.VALIDATION_ERRORS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(Validation.VALIDATION_WARNINGS + SchemaFields.TEXT_SUFFIX); fieldsCache.add(SchemaFields.METACARD_TYPE_FIELD_NAME); fieldsCache.add(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); for (String field : additionalFields) { if (StringUtils.isNotBlank(field)) { fieldsCache.add(field); } } }
Source:
public void setMessageSender(WebServiceMessageSender messageSender) { Assert.state(!this.webServiceTemplateExplicitlySet, () -> "'messageSender' must be specified on the provided: " + this.webServiceTemplate); this.webServiceTemplate.setMessageSender(messageSender); }

Target:
public void setMessageSender(WebServiceMessageSender messageSender) { setMessageSenders(messageSender); }
Source:
private void writeFromJcrProperty(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { if (!robotsContentsPropertyPath.startsWith("/")) { robotsContentsPropertyPath = request.getResource().getPath() + "/" + robotsContentsPropertyPath; } Session session = request.getResourceResolver().adaptTo(Session.class); boolean written = false; try { if (session.itemExists(robotsContentsPropertyPath)) { Item item = session.getItem(robotsContentsPropertyPath); if (item instanceof Property) { Property prop = (Property) item; int propertyType = prop.getType(); Value value = prop.getValue(); if (propertyType == PropertyType.BINARY) { Binary binary = value.getBinary(); InputStream stream = binary.getStream(); ByteStreams.copy(stream, response.getOutputStream()); written = true; } else if (propertyType == PropertyType.STRING) { response.getWriter().print(value.getString()); written = true; } } } if (!written) { log.error("no response was written while processing robots with jcr property {}", robotsContentsPropertyPath); response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { log.error("Repository Exception while processing robots with jcr property {}", robotsContentsPropertyPath, e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } }

Target:
private void writeFromJcrProperty(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { String absoluteRobotsContentsPropertyPath = robotsContentsPropertyPath; if (!absoluteRobotsContentsPropertyPath.startsWith("/")) { absoluteRobotsContentsPropertyPath = request.getResource().getPath() + "/" + robotsContentsPropertyPath; } Session session = request.getResourceResolver().adaptTo(Session.class); boolean written = false; try { if (session.itemExists(absoluteRobotsContentsPropertyPath)) { Item item = session.getItem(absoluteRobotsContentsPropertyPath); if (item instanceof Property) { Property prop = (Property) item; int propertyType = prop.getType(); Value value = prop.getValue(); if (propertyType == PropertyType.BINARY) { Binary binary = value.getBinary(); InputStream stream = binary.getStream(); ByteStreams.copy(stream, response.getOutputStream()); written = true; } else if (propertyType == PropertyType.STRING) { response.getWriter().print(value.getString()); written = true; } else { log.warn("configured property found, but type is not String or Binary.", absoluteRobotsContentsPropertyPath, PropertyType.nameFromValue(propertyType)); } } else { log.warn("Item found at configured property {}, but is not a property.", absoluteRobotsContentsPropertyPath); } } else { log.warn("configured property does not exist.", absoluteRobotsContentsPropertyPath); } if (!written) { log.error("no response was written while processing robots with jcr property {}.", absoluteRobotsContentsPropertyPath); response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { log.error("Repository Exception while processing robots with jcr property {}", absoluteRobotsContentsPropertyPath, e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
protected void doOperation() { Logic logic = new Logic(); try (Scanner scanner = new Scanner(System.in)) { System.out.println("Enter course to edit: "); String courseId = scanner.nextLine(); System.out.println("Enter new institute name: "); String institute = scanner.nextLine(); try { List<StudentAttributes> students = logic.getStudentsForCourse(courseId); for (StudentAttributes student : students) { if (student.googleId == null || student.googleId.isEmpty()) { continue; } AccountAttributes account = logic.getAccount(student.googleId); System.out.println("changed for " + account.email + " from " + account.institute + " to " + institute); account.institute = institute; logic.updateAccount(account); } } catch (Exception e) { e.printStackTrace(); } } }

Target:
protected void doOperation() { Logic logic = new Logic(); String courseId; String institute; try (Scanner scanner = new Scanner(System.in)) { System.out.println("Enter course to edit: "); courseId = scanner.nextLine(); System.out.println("Enter new institute name: "); institute = scanner.nextLine(); } try { List<StudentAttributes> students = logic.getStudentsForCourse(courseId); for (StudentAttributes student : students) { if (student.googleId == null || student.googleId.isEmpty()) { continue; } AccountAttributes account = logic.getAccount(student.googleId); System.out.println("changed for " + account.email + " from " + account.institute + " to " + institute); account.institute = institute; logic.updateAccount(account); } } catch (Exception e) { e.printStackTrace(); } }
Source:
public Path getQuarantineFile(UUID shardUuid) { return getFileSystemPath(baseQuarantineDir, shardUuid); }

Target:
public Path getQuarantineFile(UUID shardUuid) { throw new PrestoException(RAPTOR_ERROR, "Possible data corruption is detected in metadata or remote storage"); }
Source:
public HillCrestImuNode() { super(); Discovery discover = Discovery.getInstance(); discover.addListener(this); registeredDevices = new ArrayList<>(); }

Target:
public HillCrestImuNode() { super(); registeredDevices = new ArrayList<>(); Discovery discover = Discovery.getInstance(); discover.addListener(this); }
Source:
public void reloadIfOutdated(final Injector injector, final String upToDateETag) { final boolean upToDate = _cached.getETag().equals(upToDateETag); _periodicMetrics.recordCounter("cached_job_conditional_reload", upToDate ? 1 : 0); if (upToDate) { return; } LOGGER.debug() .setMessage("job is stale; reloading") .addData("jobRef", _ref) .addData("oldETag", _cached.getETag()) .addData("newETag", upToDateETag) .log(); reload(injector); }

Target:
public void reloadIfOutdated(final Injector injector, final String upToDateETag) throws NoSuchJobException { final boolean upToDate = _cached.getETag().equals(upToDateETag); _periodicMetrics.recordCounter("cached_job_conditional_reload_necessary", upToDate ? 1 : 0); if (upToDate) { return; } LOGGER.debug() .setMessage("job is stale; reloading") .addData("jobRef", _ref) .addData("oldETag", _cached.getETag()) .addData("newETag", upToDateETag) .log(); reload(injector); }
Source:
private void doSyncAndPut(PersistentCacheManager cacheManager) throws InterruptedException { CustomValue customValue = new CustomValue("value"); Cache<String, Boolean> synCache = cacheManager.getCache(SYN_CACHE_NAME, String.class, Boolean.class); Cache<Long, CustomValue> customValueCache = cacheManager.getCache(CLUSTERED_CACHE_NAME, Long.class, CustomValue.class); String firstClientStartKey = "first_client_start", firstClientEndKey = "first_client_end"; if (synCache.putIfAbsent(firstClientStartKey, true) == null) { silentPuts(customValueCache); customValueCache.put(1L, customValue); assertThat(customValueCache.get(1L), is(customValue)); synCache.put(firstClientEndKey, true); } else { silentPuts(customValueCache); int retry = 0, maxRetryCount = 30; while (++retry <= maxRetryCount && synCache.get(firstClientEndKey) == null) { Thread.sleep(1000L); } if (retry > maxRetryCount) { Assert.fail("Couldn't find " + firstClientEndKey + " in synCache after " + maxRetryCount + " retries!"); } assertThat(customValueCache.get(1L), is(customValue)); } }

Target:
private void doSyncAndPut(PersistentCacheManager cacheManager) throws InterruptedException { String customValue = "value"; Cache<String, Boolean> synCache = cacheManager.getCache(SYN_CACHE_NAME, String.class, Boolean.class); Cache<Long, String> customValueCache = cacheManager.getCache(CLUSTERED_CACHE_NAME, Long.class, String.class); String firstClientStartKey = "first_client_start", firstClientEndKey = "first_client_end"; if (synCache.putIfAbsent(firstClientStartKey, true) == null) { silentPuts(customValueCache); customValueCache.put(1L, customValue); assertThat(customValueCache.get(1L), is(customValue)); synCache.put(firstClientEndKey, true); } else { silentPuts(customValueCache); int retry = 0, maxRetryCount = 30; while (++retry <= maxRetryCount && synCache.get(firstClientEndKey) == null) { Thread.sleep(1000L); } if (retry > maxRetryCount) { Assert.fail("Couldn't find " + firstClientEndKey + " in synCache after " + maxRetryCount + " retries!"); } assertThat(customValueCache.get(1L), is(customValue)); } }
Source:
void shouldReturnIssuesDetailWhenCallWithOutstandingLink() { DetailFactory detailFactory = new DetailFactory(); Run<?, ?> owner = mock(Run.class); AnalysisResult result = mock(AnalysisResult.class); Issues<?> allIssues = mock(Issues.class); Issues<?> newIssues = mock(Issues.class); Issues<?> outstandingIssues = mock(Issues.class); Issues<?> fixedIssues = mock(Issues.class); Charset sourceEncoding = Charset.defaultCharset(); IssuesDetail parent = mock(IssuesDetail.class); Object issuesDetail = detailFactory.createTrendDetails("outstanding", owner, result, allIssues, newIssues, outstandingIssues, fixedIssues, sourceEncoding, parent); assertThat(issuesDetail).isInstanceOf(IssuesDetail.class); }

Target:
void shouldReturnIssuesDetailWhenCallWithOutstandingLink() { DetailFactory detailFactory = new DetailFactory(); Run<?, ?> owner = mock(Run.class); AnalysisResult result = mock(AnalysisResult.class); Charset sourceEncoding = Charset.defaultCharset(); IssuesDetail parent = mock(IssuesDetail.class); IssueBuilder builder = new IssueBuilder(); fixedIssues.add(builder.setMessage("fixed").build()); newIssues.add(builder.setMessage("new").build()); outstandingIssues.add(builder.setMessage("outstanding").build()); allIssues.add(builder.setMessage("all").build()); Object issuesDetail = detailFactory.createTrendDetails("outstanding", owner, result, allIssues, newIssues, outstandingIssues, fixedIssues, sourceEncoding, parent); assertThat(issuesDetail).isInstanceOf(IssuesDetail.class); assertThat(((IssuesDetail) issuesDetail).getIssues()).isEqualTo(outstandingIssues); }
Source:
private void configureAsyncJobs() { bind(JobMessageDispatcher.class).to(ArtemisJobMessageDispatcher.class); bind(SchedulerFactory.class).to(StdSchedulerFactory.class); JobManager.registerJob(TestJob1.JOB_KEY, TestJob1.class); JobManager.registerJob(ExportJob.JOB_KEY, ExportJob.class); JobManager.registerJob(ImportJob.JOB_KEY, ImportJob.class); JobManager.registerJob(org.candlepin.async.tasks.RefreshPoolsJob.JOB_KEY, org.candlepin.async.tasks.RefreshPoolsJob.class); }

Target:
private void configureAsyncJobs() { bind(JobMessageDispatcher.class).to(ArtemisJobMessageDispatcher.class); bind(SchedulerFactory.class).to(StdSchedulerFactory.class); JobManager.registerJob(TestJob1.JOB_KEY, TestJob1.class); JobManager.registerJob(ExportJob.JOB_KEY, ExportJob.class); JobManager.registerJob(ImportJob.JOB_KEY, ImportJob.class); JobManager.registerJob(RefreshPoolsForProductJob.JOB_KEY, RefreshPoolsForProductJob.class); JobManager.registerJob(RefreshPoolsJob.JOB_KEY, RefreshPoolsJob.class); }
Source:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { m_associatedAlarms.clear(); alarms.stream().forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); }

Target:
public void setRelatedAlarms(Set<OnmsAlarm> alarms) { m_associatedAlarms.clear(); alarms.forEach(relatedAlarm -> m_associatedAlarms.add(new AlarmAssociation(this, relatedAlarm))); }
Source:
public Map<String, Object> toMap() { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = super.toMap(); try { map.put(STREAM, stream != null ? mapper.writeValueAsString(stream) : ""); map.put(ACTIONS, actions != null ? mapper.writerFor(new TypeReference<List<Action>>() { }).writeValueAsString(actions) : ""); } catch (Exception e) { throw new RuntimeException(e); } return map; }

Target:
public Map<String, Object> toMap() { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = super.toMap(); try { map.put(ACTIONS, actions != null ? mapper.writerFor(new TypeReference<List<Action>>() { }).writeValueAsString(actions) : ""); } catch (Exception e) { throw new RuntimeException(e); } return map; }
Source:
public GoogleCloudStorageImpl( GoogleCloudStorageOptions options, HttpRequestInitializer httpRequestInitializer) throws IOException { Preconditions.checkNotNull(options, "options must not be null"); options.throwIfNotValid(); logger.atFine().log("GCS(%s)", options.getAppName()); this.storageOptions = options; this.httpRequestInitializer = httpRequestInitializer; HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); this.gcs = new Storage.Builder(httpTransport, JSON_FACTORY, httpRequestInitializer) .setRootUrl(options.getStorageRootUrl()) .setServicePath(options.getStorageServicePath()) .setApplicationName(options.getAppName()) .build(); if (storageOptions.isGrpcEnabled()) { this.storageStubProvider = new StorageStubProvider(options.getReadChannelOptions(), backgroundTasksThreadPool); } initAuthorizationProvider(storageOptions.getAuthorizationProvider(), storageOptions.getAuthorizationProviderInitArgument()); }

Target:
public GoogleCloudStorageImpl( GoogleCloudStorageOptions options, HttpRequestInitializer httpRequestInitializer) throws IOException { Preconditions.checkNotNull(options, "options must not be null"); options.throwIfNotValid(); logger.atFine().log("GCS(%s)", options.getAppName()); this.storageOptions = options; this.httpRequestInitializer = httpRequestInitializer; HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); this.gcs = new Storage.Builder(httpTransport, JSON_FACTORY, httpRequestInitializer) .setRootUrl(options.getStorageRootUrl()) .setServicePath(options.getStorageServicePath()) .setApplicationName(options.getAppName()) .build(); if (storageOptions.isGrpcEnabled()) { this.storageStubProvider = new StorageStubProvider(options.getReadChannelOptions(), backgroundTasksThreadPool); } storageRequestAuthorizer = initializeStorageRequestAuthorizer(storageOptions); }
Source:
public void testException() { BundleMessageDataContainerDto dto = new BundleMessageDataContainerDto(makeActions()); getStub(FindEventsQueryDto.class).failWith(new ProtocolAdapterException("simulate error")); List<ActionResponseDto> result = callExecutors(dto); Assert.assertTrue(result != null); }

Target:
public void testException() { final List<ActionDto> actionDtoList = this.makeActions(); BundleMessageDataContainerDto dto = new BundleMessageDataContainerDto(actionDtoList); getStub(FindEventsQueryDto.class).failWith(new ProtocolAdapterException("simulate error")); List<ActionResponseDto> result = callExecutors(dto); Assert.assertTrue(result != null); Assert.assertEquals(actionDtoList.size(), result.size()); }
Source:
public Measurement addMeasurement(String report_id, Boolean write_file) { Measurement measurement = new Measurement(); measurement.report_id = report_id; measurement.is_done = true; measurement.is_uploaded = true; measurement.save(); if (write_file){ File entryFile = Measurement.getEntryFile(c, measurement.id, measurement.test_name); entryFile.getParentFile().mkdirs(); try { FileUtils.writeStringToFile( entryFile, "", Charset.forName("UTF-8") ); } catch (IOException e) { e.printStackTrace(); } } return measurement; }

Target:
private Measurement addMeasurement(String report_id, Boolean write_file) throws IOException { Measurement measurement = new Measurement(); measurement.report_id = report_id; measurement.is_done = true; measurement.is_uploaded = true; measurement.save(); if (write_file){ File entryFile = Measurement.getEntryFile(c, measurement.id, measurement.test_name); entryFile.getParentFile().mkdirs(); FileUtils.writeStringToFile( entryFile, "", Charset.forName("UTF-8") ); } return measurement; }
Source:
public String intercept(ActionInvocation invocation) throws Exception { ActionContext context = invocation.getInvocationContext(); HttpServletRequest request = context.getServletRequest(); addVaryHeaders(invocation); String contextPath = request.getContextPath(); if (exemptedPaths.contains(contextPath)) { return invocation.invoke(); } if (resourceIsolationPolicy.isRequestAllowed(request)) { return invocation.invoke(); } LOG.debug("Fetch metadata rejected cross-origin request to [{}]", contextPath); return SC_FORBIDDEN; }

Target:
public String intercept(ActionInvocation invocation) throws Exception { ActionContext context = invocation.getInvocationContext(); HttpServletRequest request = context.getServletRequest(); addVaryHeaders(invocation); String contextPath = request.getContextPath(); if (exemptedPaths.contains(contextPath)) { return invocation.invoke(); } if (resourceIsolationPolicy.isRequestAllowed(request)) { return invocation.invoke(); } LOG.info("Fetch metadata rejected cross-origin request to [{}]", contextPath); return SC_FORBIDDEN; }
Source:
private Object readResolve() throws ObjectStreamException { try { String[] names = id.split("#"); Field opField = Class.forName(names[0]).getDeclaredField(names[1]); return opField.get(null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }

Target:
private Object readResolve() throws ObjectStreamException { try { String[] names = id.split("#"); Field opField = Class.forName(names[0]).getField(names[1]); return opField.get(null); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
public boolean isDiscoveryNode() { return id.length > 64; }

Target:
public boolean isDiscoveryNode() { return isFakeNodeId; }
Source:
public void visitToken(DetailAST arrayInit) { final DetailAST rcurly = arrayInit.findFirstToken(TokenTypes.RCURLY); final DetailAST previousSibling = rcurly.getPreviousSibling(); if (arrayInit.getChildCount() != 1 && (alwaysDemandTrailingComma || !TokenUtil.areOnSameLine(rcurly, previousSibling)) && (alwaysDemandTrailingComma || !TokenUtil.areOnSameLine(arrayInit, previousSibling)) && previousSibling.getType() != TokenTypes.COMMA) { log(previousSibling, MSG_KEY); } }

Target:
public void visitToken(DetailAST arrayInit) { final DetailAST rcurly = arrayInit.findFirstToken(TokenTypes.RCURLY); final DetailAST previousSibling = rcurly.getPreviousSibling(); if (arrayInit.getChildCount() != 1 && (alwaysDemandTrailingComma || !TokenUtil.areOnSameLine(rcurly, previousSibling) && !TokenUtil.areOnSameLine(arrayInit, previousSibling)) && previousSibling.getType() != TokenTypes.COMMA) { log(previousSibling, MSG_KEY); } }
Source:
protected String[] customCommandLineValidation() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsReadable(EXTENDED_ILLUMINA_MANIFEST); IOUtil.assertFileIsWritable(OUTPUT); refSeq = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE); final SAMSequenceDictionary sequenceDictionary = refSeq.getSequenceDictionary(); if (!sequenceDictionary.getSequence(0).getAssembly().equals("GRCh37")) { return new String[]{"This tool is currently only implemented to support NCBI Build 37 / HG19 Reference Sequence."}; } if (FINGERPRINT_GENOTYPES_VCF_FILE != null) { IOUtil.assertFileIsReadable(FINGERPRINT_GENOTYPES_VCF_FILE); } if (GENDER_GTC != null) { IOUtil.assertFileIsReadable(GENDER_GTC); } return super.customCommandLineValidation(); }

Target:
protected String[] customCommandLineValidation() { IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsReadable(EXTENDED_ILLUMINA_MANIFEST); IOUtil.assertFileIsWritable(OUTPUT); refSeq = ReferenceSequenceFileFactory.getReferenceSequenceFile(REFERENCE_SEQUENCE); final SAMSequenceDictionary sequenceDictionary = refSeq.getSequenceDictionary(); final String assembly = sequenceDictionary.getSequence(0).getAssembly(); if (!assembly.equals("GRCh37")) { return new String[]{"The selected reference sequence ('" + assembly + "') is not supported. This tool is currently only implemented to support NCBI Build 37 / HG19 Reference Sequence."}; } if (FINGERPRINT_GENOTYPES_VCF_FILE != null) { IOUtil.assertFileIsReadable(FINGERPRINT_GENOTYPES_VCF_FILE); } if (GENDER_GTC != null) { IOUtil.assertFileIsReadable(GENDER_GTC); } return super.customCommandLineValidation(); }
Source:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { log.info("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); context.getContextData().put("ClientInterceptorInvoked", this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); context.sendRequest(); }

Target:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { log.debug("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); context.sendRequest(); }
Source:
private List<DiskImage> getImagesToPreview() { if (imagesToPreview == null) { List<DiskImage> allSnapshotsForVm = diskImageDao.getAllSnapshotsForVmSnapshot(getDstSnapshot().getId()); Set<Guid> guidsAllSnapshotsForVm = allSnapshotsForVm.stream() .map(BaseDisk::getId) .collect(Collectors.toSet()); if (getParameters().getDiskIds() != null) { imagesToPreview = getParameters().getDiskIds().stream() .filter(guidsAllSnapshotsForVm::contains) .map(g -> diskImageDao.getSnapshotById(g)) .collect(Collectors.toList()); } else { imagesToPreview = allSnapshotsForVm; } } return imagesToPreview; }

Target:
private List<DiskImage> getImagesToPreview() { if (imagesToPreview == null) { List<DiskImage> allSnapshotsForVm = diskImageDao.getAllSnapshotsForVmSnapshot(getDstSnapshot().getId()); if (getParameters().getDiskIds() != null) { Map<Guid, DiskImage> guidDiskImageMap = allSnapshotsForVm.stream() .collect(Collectors.toMap(BaseDisk::getId, disk -> disk)); diskImagesForDiskIds = guidDiskImageMap.entrySet().stream() .filter(entry -> getParameters().getDiskIds().contains(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.toList()); imagesToPreview = diskImagesForDiskIds; } else { imagesToPreview = allSnapshotsForVm; } } return imagesToPreview; }
Source:
public void afterExam() throws Exception { getServiceManager().stopManagedService(openSearchPid); getServiceManager().stopManagedService(cswPid); getServiceManager().stopManagedService(cswPid2); getServiceManager().stopManagedService(cswPid3); getServiceManager().stopManagedService(gmdPid); if (cswServer != null) { cswServer.stop(); } }

Target:
public void afterExam() throws Exception { if (openSearchPid != null) { getServiceManager().stopManagedService(openSearchPid); } if (cswPid != null) { getServiceManager().stopManagedService(cswPid); } if (cswPid2 != null) { getServiceManager().stopManagedService(cswPid2); } if (cswPid3 != null) { getServiceManager().stopManagedService(cswPid3); } if (gmdPid != null) { getServiceManager().stopManagedService(gmdPid); } if (cswServer != null) { cswServer.stop(); } }
Source:
public void startingVmCompleted(Guid vmId, String cause) { if (log.isDebugEnabled() && startingVms.contains(vmId)) { log.debug("Startup of VM completed ({})", vmId, cause); } startingVms.remove(vmId); }

Target:
public void startingVmCompleted(Guid vmId, String cause) { if (startingVms.remove(vmId)) { log.debug("Startup of VM completed ({})", vmId, cause); } }
Source:
private List<Integer> generateIntegerList(final int size) { final List<Integer> integerList = new ArrayList<Integer>(size); for (int i = 0; i < size; i++) { integerList.add(random.nextInt()); } return integerList; }

Target:
private List<Integer> generateIntegerList(final int size) { final List<Integer> integerList = new ArrayList<>(size); for (int i = 0; i < size; i++) { integerList.add(random.nextInt()); } return integerList; }
Source:
public void send_request(ClientRequestInfo clientRequestInfo) throws ForwardRequest { if (openTracingService == null) { return; } Tracer tracer = GlobalTracer.get(); if (!GlobalTracer.isRegistered()) { Tracer tracerImpl = openTracingService.getTracer(PAYARA_CORBA_RMI_TRACER_NAME); if (tracerImpl == null) { return; } else { GlobalTracer.register(tracerImpl); } } Span activeSpan = tracer.activeSpan(); if (activeSpan == null) { return; } OpenTracingIiopTextMap textMap = new OpenTracingIiopTextMap(); tracer.inject(activeSpan.context(), Format.Builtin.TEXT_MAP, textMap); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(textMap); out.flush(); ServiceContext serviceContext = new ServiceContext(OPENTRACING_IIOP_ID, bos.toByteArray()); clientRequestInfo.add_request_service_context(serviceContext, true); } catch (IOException ex) { Logger.getLogger(OpenTracingIiopClientInterceptor.class.getName()).log(Level.SEVERE, "Exception caught propagating span context"); } }

Target:
public void send_request(ClientRequestInfo clientRequestInfo) throws ForwardRequest { if (!GlobalTracer.isRegistered()) { registerTracer(); if (!GlobalTracer.isRegistered()) { return; } } Span activeSpan = tracer.activeSpan(); if (activeSpan == null) { return; } OpenTracingIiopTextMap textMap = new OpenTracingIiopTextMap(); tracer.inject(activeSpan.context(), Format.Builtin.TEXT_MAP, textMap); try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos)) { out.writeObject(textMap); out.flush(); ServiceContext serviceContext = new ServiceContext(OPENTRACING_IIOP_ID, bos.toByteArray()); clientRequestInfo.add_request_service_context(serviceContext, true); } catch (IOException ex) { Logger.getLogger(OpenTracingIiopClientInterceptor.class.getName()).log(Level.SEVERE, "Exception caught propagating span context"); } }
Source:
public void createNoAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(false); getClient(null).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isUnauthorized()); }

Target:
public void createNoAccess() throws Exception { ObjectMapper mapper = new ObjectMapper(); BitstreamFormatRest bitstreamFormatRest = this.createRandomMockBitstreamRest(false); getClient(null).perform(post("/api/core/bitstreamformats/") .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isUnauthorized()); getClient().perform(get("/api/core/bitstreamformats/")) .andExpect(status().isOk()) .andExpect(jsonPath("$.page.totalElements", is(DEFAULT_AMOUNT_FORMATS))); }
Source:
private static SwitchType getSwitchType(Version clusterVersion, Map<String, Object> networkProperties) { Object switchType = networkProperties.get(VdsProperties.SWITCH_KEY); boolean switchTypeShouldBeReportedByOvs = FeatureSupported.ovsSupported(clusterVersion); if (switchTypeShouldBeReportedByOvs && switchType == null) { throw new IllegalStateException("Required SwitchType is not reported."); } return switchType != null ? SwitchType.parse(switchType.toString()) : null; }

Target:
private static SwitchType getSwitchType(Version clusterVersion, Map<String, Object> networkProperties) { Object switchType = networkProperties.get(VdsProperties.SWITCH_KEY); boolean switchTypeShouldBeReportedByVdsm = FeatureSupported.ovsSupported(clusterVersion); if (switchTypeShouldBeReportedByVdsm && switchType == null) { throw new IllegalStateException("Required SwitchType is not reported."); } return SwitchType.parse(Objects.toString(switchType, null)); }
Source:
protected void bind(@NonNull User user) { Statistics statistics = user.getStats(); episodes.setValue(statistics.getWatchedEpisodes()); hours.setValue((int) (statistics.getWatchedHours() + 0.5F)); days.setValue((int) (statistics.getWatchedDays() + 0.5F)); Observable.from(user.getFriends()) .compose(bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribeOn(Schedulers.computation()) .filter(f -> f.getWastedTime() > user.getWastedTime()) .count() .observeOn(AndroidSchedulers.mainThread()) .subscribe(n -> place.setText(getActivity().getString(R.string.place, n + 1))); }

Target:
protected void bind(@NonNull User user) { Statistics statistics = user.getStats(); episodes.setValue(statistics.getWatchedEpisodes()); hours.setValue((int) Math.ceil(statistics.getWatchedHours())); days.setValue((int) Math.ceil(statistics.getWatchedDays())); Observable.from(user.getFriends()) .compose(bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribeOn(Schedulers.computation()) .filter(f -> f.getWastedTime() > user.getWastedTime()) .count() .observeOn(AndroidSchedulers.mainThread()) .subscribe(n -> place.setText(getActivity().getString(R.string.place, n + 1))); }
Source:
public StructuredRecord.Builder startCurrentValue() throws IOException, InterruptedException { if (schema != null) { return recordTransformer.transform(delegate.getCurrentKey().datum(), schema, pathField); } Schema schema = recordTransformer.generateStructuredSchema(delegate.getCurrentKey().datum()); return recordTransformer.transform(delegate.getCurrentKey().datum(), addFieldToSchema(schema, pathField), pathField); }

Target:
public StructuredRecord.Builder startCurrentValue() throws IOException, InterruptedException { GenericRecord genericRecord = delegate.getCurrentKey().datum(); Schema recordSchema = schema; if (recordSchema == null) { recordSchema = recordTransformer.convertSchema(genericRecord.getSchema()); if (pathField != null) { recordSchema = addFieldToSchema(recordSchema, pathField); } } return recordTransformer.transform(genericRecord, recordSchema, pathField); }
Source:
void fillChunks() { try { PutChunk chunkToFill; while (!isChunkFillingDone()) { if (channelReadBuffer == null) { channelReadBuffer = chunkFillerChannel.getNextChunk(0); } if (channelReadBuffer != null) { maybeStopTrackingWaitForChannelDataTime(); chunkToFill = getChunkToFill(); if (chunkToFill == null) { maybeStartTrackingWaitForChunkTime(); break; } else { maybeStopTrackingWaitForChunkTime(); bytesFilledSoFar += chunkToFill.fillFrom(channelReadBuffer); if (chunkToFill.isReady()) { routerCallback.onPollReady(); } if (!channelReadBuffer.hasRemaining()) { chunkFillerChannel.resolveOldestChunk(null); channelReadBuffer = null; } } } else { if (getFreeChunk() != null) { maybeStartTrackingWaitForChannelDataTime(); } break; } } if (chunkFillingCompletedSuccessfully) { PutChunk lastChunk = getBuildingChunk(); if (lastChunk != null) { if (chunkCounter != 0 && lastChunk.buf.position() == 0) { logger.trace("The last buffer(s) received from chunkFillerChannel have no data, discarding them."); } else { lastChunk.onFillComplete(true, true); updateChunkFillerWaitTimeMetrics(); } } routerCallback.onPollReady(); } } catch (Exception e) { RouterException routerException = e instanceof RouterException ? (RouterException) e : new RouterException("PutOperation fillChunks encountered unexpected error", e, RouterErrorCode.UnexpectedInternalError); routerMetrics.chunkFillerUnexpectedErrorCount.inc(); routerCallback.onPollReady(); setOperationExceptionAndComplete(routerException); } }

Target:
void fillChunks() { try { PutChunk chunkToFill; while (!isChunkFillingDone()) { if (channelReadBuffer == null) { channelReadBuffer = chunkFillerChannel.getNextChunk(0); } if (channelReadBuffer != null) { maybeStopTrackingWaitForChannelDataTime(); chunkToFill = getChunkToFill(); if (chunkToFill == null) { maybeStartTrackingWaitForChunkTime(); break; } else { maybeStopTrackingWaitForChunkTime(); bytesFilledSoFar += chunkToFill.fillFrom(channelReadBuffer); if (chunkToFill.isReady() && !chunkToFill.chunkBlobProperties.isEncrypted()) { routerCallback.onPollReady(); } if (!channelReadBuffer.hasRemaining()) { chunkFillerChannel.resolveOldestChunk(null); channelReadBuffer = null; } } } else { if (getFreeChunk() != null) { maybeStartTrackingWaitForChannelDataTime(); } break; } } if (chunkFillingCompletedSuccessfully) { PutChunk lastChunk = getBuildingChunk(); if (lastChunk != null) { if (chunkCounter != 0 && lastChunk.buf.position() == 0) { logger.trace("The last buffer(s) received from chunkFillerChannel have no data, discarding them."); } else { lastChunk.onFillComplete(true); updateChunkFillerWaitTimeMetrics(); } if (lastChunk.isReady()) { routerCallback.onPollReady(); } } } } catch (Exception e) { RouterException routerException = e instanceof RouterException ? (RouterException) e : new RouterException("PutOperation fillChunks encountered unexpected error", e, RouterErrorCode.UnexpectedInternalError); routerMetrics.chunkFillerUnexpectedErrorCount.inc(); routerCallback.onPollReady(); setOperationExceptionAndComplete(routerException); } }
Source:
protected void fireEvalStateChanged() { Runnable r= new Runnable() { @Override public void run() { Shell shell= getShell(); if (fSnippetStateListeners != null && shell != null && !shell.isDisposed()) { for (ISnippetStateChangedListener l : new ArrayList<>(fSnippetStateListeners)) { l.snippetStateChanged(JavaSnippetEditor.this); } } } }; Shell shell= getShell(); if (shell != null) { getShell().getDisplay().asyncExec(r); } }

Target:
protected void fireEvalStateChanged() { Runnable r= new Runnable() { @Override public void run() { Shell shell= getShell(); if (fSnippetStateListeners != null && shell != null && !shell.isDisposed()) { for (ISnippetStateChangedListener listener : new ArrayList<>(fSnippetStateListeners)) { listener.snippetStateChanged(JavaSnippetEditor.this); } } } }; Shell shell= getShell(); if (shell != null) { getShell().getDisplay().asyncExec(r); } }
Source:
public BlockManagerImpl(final Configuration conf, final StorageContainerManager scm) { Objects.requireNonNull(scm, "SCM cannot be null"); this.pipelineManager = scm.getPipelineManager(); this.containerManager = scm.getContainerManager(); this.containerSize = (long)conf.getStorageSize( ScmConfigKeys.OZONE_SCM_CONTAINER_SIZE, ScmConfigKeys.OZONE_SCM_CONTAINER_SIZE_DEFAULT, StorageUnit.BYTES); mxBean = MBeans.register("BlockManager", "BlockManagerImpl", this); deletedBlockLog = new DeletedBlockLogImpl(conf, scm.getContainerManager(), scm.getScmMetadataStore()); long svcInterval = conf.getTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL, OZONE_BLOCK_DELETING_SERVICE_INTERVAL_DEFAULT, TimeUnit.MILLISECONDS); long serviceTimeout = conf.getTimeDuration( OZONE_BLOCK_DELETING_SERVICE_TIMEOUT, OZONE_BLOCK_DELETING_SERVICE_TIMEOUT_DEFAULT, TimeUnit.MILLISECONDS); blockDeletingService = new SCMBlockDeletingService(deletedBlockLog, containerManager, scm.getScmNodeManager(), scm.getEventQueue(), svcInterval, serviceTimeout, conf); safeModePrecheck = new SafeModePrecheck(conf); long heartbeatInterval = conf.getTimeDuration( HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL, HddsConfigKeys.HDDS_COMMAND_STATUS_REPORT_INTERVAL, TimeUnit.MILLISECONDS); long commandStatusReportInterval = conf.getTimeDuration( HddsConfigKeys.HDDS_COMMAND_STATUS_REPORT_INTERVAL, HddsConfigKeys.HDDS_COMMAND_STATUS_REPORT_INTERVAL_DEFAULT, TimeUnit.MILLISECONDS); Preconditions.checkState(heartbeatInterval <= commandStatusReportInterval, "Heartbeat interval is smaller than command status report interval"); pipelineCreateWaitTimeout = ((commandStatusReportInterval + heartbeatInterval - 1) / heartbeatInterval) * heartbeatInterval + 5000L; }

Target:
public BlockManagerImpl(final Configuration conf, final StorageContainerManager scm) { Objects.requireNonNull(scm, "SCM cannot be null"); this.pipelineManager = scm.getPipelineManager(); this.containerManager = scm.getContainerManager(); this.containerSize = (long)conf.getStorageSize( ScmConfigKeys.OZONE_SCM_CONTAINER_SIZE, ScmConfigKeys.OZONE_SCM_CONTAINER_SIZE_DEFAULT, StorageUnit.BYTES); mxBean = MBeans.register("BlockManager", "BlockManagerImpl", this); deletedBlockLog = new DeletedBlockLogImpl(conf, scm.getContainerManager(), scm.getScmMetadataStore()); long svcInterval = conf.getTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL, OZONE_BLOCK_DELETING_SERVICE_INTERVAL_DEFAULT, TimeUnit.MILLISECONDS); long serviceTimeout = conf.getTimeDuration( OZONE_BLOCK_DELETING_SERVICE_TIMEOUT, OZONE_BLOCK_DELETING_SERVICE_TIMEOUT_DEFAULT, TimeUnit.MILLISECONDS); blockDeletingService = new SCMBlockDeletingService(deletedBlockLog, containerManager, scm.getScmNodeManager(), scm.getEventQueue(), svcInterval, serviceTimeout, conf); safeModePrecheck = new SafeModePrecheck(conf); }
Source:
public void testExecute_curlLogger() throws Exception { LogRecordingHandler recorder = new LogRecordingHandler(); HttpTransport.LOGGER.setLevel(Level.CONFIG); HttpTransport.LOGGER.addHandler(recorder); new MockHttpTransport() .createRequestFactory() .buildGetRequest(new GenericUrl("<LINK_0>'b'c")) .execute(); boolean found = false; for (String message : recorder.messages()) { if (message.startsWith("curl")) { found = true; assert(message.contains("curl -v --compressed -H 'Accept-Encoding: gzip'")); assert(message.contains("-H 'User-Agent: Google-HTTP-Java-Client/" + HttpRequest.VERSION + " (gzip)'")); assert(message.contains("' -- '<LINK_0>'\"'\"'b'\"'\"'c'")); } } assertTrue(found); }

Target:
public void testExecute_curlLogger() throws Exception { LogRecordingHandler recorder = new LogRecordingHandler(); HttpTransport.LOGGER.setLevel(Level.CONFIG); HttpTransport.LOGGER.addHandler(recorder); new MockHttpTransport() .createRequestFactory() .buildGetRequest(new GenericUrl("<LINK_0>'b'c")) .execute(); boolean found = false; for (String message : recorder.messages()) { if (message.startsWith("curl")) { found = true; assertTrue(message.contains("curl -v --compressed -H 'Accept-Encoding: gzip'")); assertTrue(message.contains("-H 'User-Agent: Google-HTTP-Java-Client/" + HttpRequest.VERSION + " (gzip)'")); assertTrue(message.contains("' -- '<LINK_0>'\"'\"'b'\"'\"'c'")); } } assertTrue(found); }
Source:
public ResponseEntity<Integer> createTransaction( @PathVariable final String cropName, @PathVariable final String lotId, @ApiParam("Transaction to be created") @RequestBody final TransactionDto transactionDto) { final String userName = SecurityUtil.getLoggedInUserName(); final WorkbenchUser user = this.userService.getUserByUsername(userName); transactionDto.setUser(user.getUserid().toString()); return new ResponseEntity<>(this.transactionService.saveTransaction(transactionDto, lotId, TransactionStatus.COMMITTED), HttpStatus.CREATED); }

Target:
public ResponseEntity<Integer> createTransaction( @PathVariable final String cropName, @PathVariable final String lotId, @ApiParam("Transaction to be created") @RequestBody final TransactionDto transactionDto) { final WorkbenchUser user = this.securityService.getCurrentlyLoggedInUser(); transactionDto.setUser(user.getUserid().toString()); if (transactionDto.getLot() == null) { transactionDto.setLot(new ExtendedLotDto()); } transactionDto.getLot().setLotId(Integer.valueOf(lotId)); return new ResponseEntity<>(this.transactionService.saveTransaction(transactionDto), HttpStatus.CREATED); }