auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected static void configNestedHVSupport(VirtualMachineMO vmMo, VirtualMachineTO vmSpec, VirtualMachineConfigSpec vmConfigSpec) throws Exception { VmwareContext context = vmMo.getContext(); if ("true".equals(vmSpec.getDetails().get(VmDetailConstants.NESTED_VIRTUALIZATION_FLAG))) { if (s_logger.isDebugEnabled()) s_logger.debug("Nested Virtualization enabled in configuration, checking hypervisor capability"); ManagedObjectReference hostMor = vmMo.getRunningHost().getMor(); ManagedObjectReference computeMor = context.getVimClient().getMoRefProp(hostMor, "parent"); ManagedObjectReference environmentBrowser = context.getVimClient().getMoRefProp(computeMor, "environmentBrowser"); HostCapability hostCapability = context.getService().queryTargetCapabilities(environmentBrowser, hostMor); Boolean nestedHvSupported = hostCapability.isNestedHVSupported(); if (nestedHvSupported == null) { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName()); } else if (nestedHvSupported.booleanValue()) { s_logger.debug("Hypervisor supports nested virtualization, enabling for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(true); } else { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(false); } } }

Target:
protected void configNestedHVSupport(VirtualMachineMO vmMo, VirtualMachineTO vmSpec, VirtualMachineConfigSpec vmConfigSpec) throws Exception { VmwareContext context = vmMo.getContext(); if ("true".equals(vmSpec.getDetails().get(VmDetailConstants.NESTED_VIRTUALIZATION_FLAG))) { if (s_logger.isDebugEnabled()) s_logger.debug("Nested Virtualization enabled in configuration, checking hypervisor capability"); ManagedObjectReference hostMor = vmMo.getRunningHost().getMor(); ManagedObjectReference computeMor = context.getVimClient().getMoRefProp(hostMor, "parent"); ManagedObjectReference environmentBrowser = context.getVimClient().getMoRefProp(computeMor, "environmentBrowser"); HostCapability hostCapability = context.getService().queryTargetCapabilities(environmentBrowser, hostMor); Boolean nestedHvSupported = hostCapability.isNestedHVSupported(); if (nestedHvSupported == null) { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName()); } else if (nestedHvSupported.booleanValue()) { s_logger.debug("Hypervisor supports nested virtualization, enabling for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(true); } else { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(false); } } }
Source:
protected void parseHeader(BufferedReader reader, String groupSep) throws IOException { splitNextLine(reader, groupSep) .map(parts -> { int count = parts.length; if (count < 3) throw new IllegalArgumentException("Expected at least 2 columns, got: " + count); groupNames.clear(); for (int i = 1; i < count - 1; i++) { groupNames.add(parts[i]); } return groupNames; }). orElseThrow(() -> new IllegalArgumentException("No header line")); }

Target:
protected void parseHeader(BufferedReader reader, String groupSep) throws IOException { splitNextLine(reader, groupSep) .map(parts -> Collections.addAll(groupNames, stripHeadAndTail(parts))) .orElseThrow(() -> new IllegalArgumentException("No header line")); }
Source:
public void testDefaultTimeOfMeetingIs30Minutes() { ExcelReader excelReader = new ExcelReader(EXCEL_INPUT_DATA); List<Map<String, String>> meetingData = excelReader.getMapValues("MeetingData"); String organizer = meetingData.get(0).get("Organizer"); String subject = meetingData.get(0).get("Subject"); String attendee = meetingData.get(0).get("Attendee"); String body = meetingData.get(0).get("Body"); HomeTabletPage homePage = new HomeTabletPage(); SchedulePage schedulePage = homePage.clickScheduleBtn(); int durationMeeting = schedulePage.setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setAttendeeTxtBoxPressingEnter(attendee) .setBodyTxtBox(body) .getDurationOfMeetingByDefault(); Assert.assertEquals(30, durationMeeting); }

Target:
public void testDefaultTimeOfMeetingIs30Minutes() { HomeTabletPage homeTabletPage = new HomeTabletPage(); SchedulePage schedulePage = homeTabletPage.clickScheduleBtn(); Assert.assertEquals(schedulePage.getDurationOfMeetingByDefault(), 30); }
Source:
private FileAssetDto convertFileResourceToDto(AttachResource resource){ FileAssetDto.FileAssetDtoBuilder builder = FileAssetDto.builder() .id(resource.getId()) .name(resource.getMasterFileName()) .description(resource.getDescription()) .createdAt(resource.getCreationDate()) .updatedAt(resource.getLastModified()) .group(resource.getMainGroup()) .path(resource.getAttachPath()) .size(resource.getDefaultInstance().getFileLength()); for (Category category : resource.getCategories()) { builder.category(category.getCode()); } return builder.build(); }

Target:
private FileAssetDto convertFileResourceToDto(AttachResource resource){ return FileAssetDto.builder() .id(resource.getId()) .name(resource.getMasterFileName()) .description(resource.getDescription()) .createdAt(resource.getCreationDate()) .updatedAt(resource.getLastModified()) .group(resource.getMainGroup()) .path(resource.getAttachPath()) .size(resource.getDefaultInstance().getFileLength()) .categories(resource.getCategories().stream() .map(Category::getCode).collect(Collectors.toList())) .build(); }
Source:
private User getUser() { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = runAsSystem(() -> userService.getUser(userDetails.getUsername())); if (user != null) { return user; } else { throw new UsernameNotFoundException("Can't find user: [" + userDetails.getUsername() + "]"); } }

Target:
private User getUser() { User user = userService.getUser(SecurityUtils.getCurrentUsername()); if (user != null) { return user; } else { throw new UsernameNotFoundException("Can't find user: [" + SecurityUtils.getCurrentUsername() + "]"); } }
Source:
private ServerBootstrap serverBootstrap() { return new ServerBootstrap() .group(this.bossGroup, this.childGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(logLevel)) .option(ChannelOption.SO_BACKLOG, 128) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(this.channelInitializer(true)) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .validate(); }

Target:
private ServerBootstrap serverBootstrap() { return new ServerBootstrap() .group(this.bossGroup, this.childGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(logLevel)) .option(ChannelOption.SO_BACKLOG, 128) .childHandler(this.channelInitializer(true)) .childOption(ChannelOption.SO_KEEPALIVE, true) .validate(); }
Source:
private InstructorAttributes extractUpdatedInstructor(String courseId, InstructorCreateRequest instructorRequest) { String instructorRole = instructorRequest.getRoleName(); String displayedName = instructorRequest.getDisplayName(); if (displayedName == null || displayedName.isEmpty()) { displayedName = InstructorAttributes.DEFAULT_DISPLAY_NAME; } instructorRole = SanitizationHelper.sanitizeName(instructorRole); displayedName = SanitizationHelper.sanitizeName(displayedName); InstructorAttributes instructorToEdit = updateBasicInstructorAttributes(courseId, instructorRequest.getId(), instructorRequest.getName(), instructorRequest.getEmail(), instructorRole, instructorRequest.getIsDisplayedToStudent(), displayedName); if (instructorRole.equals(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_CUSTOM)) { updateInstructorCourseLevelPrivileges(instructorToEdit); } updateInstructorWithSectionLevelPrivileges(courseId, instructorToEdit); instructorToEdit.privileges.validatePrivileges(); return instructorToEdit; }

Target:
private InstructorAttributes extractUpdatedInstructor(String courseId, InstructorCreateRequest instructorRequest) { InstructorAttributes instructorToEdit = retrieveEditedInstructor(courseId, instructorRequest.getId(), instructorRequest.getName(), instructorRequest.getEmail(), instructorRequest.getRoleName(), instructorRequest.getIsDisplayedToStudent(), instructorRequest.getDisplayName()); if (instructorToEdit.getRole().equals(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_CUSTOM)) { updateInstructorCourseLevelPrivileges(instructorToEdit); } updateInstructorWithSectionLevelPrivileges(courseId, instructorToEdit); instructorToEdit.privileges.validatePrivileges(); return instructorToEdit; }
Source:
public DeferredResult<MergeCollection> searchMerge( @ApiParam(value="The source branch path to match") @RequestParam(value="source", required = false) final String source, @ApiParam(value="The target branch path to match") @RequestParam(value="target", required = false) final String target, @ApiParam(value="The current status of the request") @RequestParam(value="status", required = false) final Merge.Status status) { return DeferredResults.wrap(RepositoryRequests.merging() .prepareSearch() .filterBySource(source) .filterByTarget(target) .filterByStatus(status.name()) .build(repositoryId) .execute(bus)); }

Target:
public DeferredResult<MergeCollection> searchMerge( @ApiParam(value="The source branch path to match") @RequestParam(value="source", required = false) final String source, @ApiParam(value="The target branch path to match") @RequestParam(value="target", required = false) final String target, @ApiParam(value="The current status of the request") @RequestParam(value="status", required = false) final Merge.Status status) { return DeferredResults.wrap(RepositoryRequests.merging() .prepareSearch() .filterBySource(source) .filterByTarget(target) .filterByStatus(status != null ? status.name() : null) .build(repositoryId) .execute(bus)); }
Source:
private void processSurveys(final DatastoreService ds) { final Query q = new Query("SurveyGroup"); final PreparedQuery pq = ds.prepare(q); for (Entity form : pq.asIterable(FetchOptions.Builder.withChunkSize(500))) { Long id = form.getKey().getId(); String type = (String) form.getProperty("projectType"); String name = (String) form.getProperty("name"); if ("PROJECT".contentEquals(type)) { surveys.add(id); nameOfSurvey.put(id, name); } } }

Target:
private void processSurveys(final DatastoreService ds) { final Query q = new Query("SurveyGroup"); final PreparedQuery pq = ds.prepare(q); for (Entity survey : pq.asIterable(FetchOptions.Builder.withChunkSize(500))) { Long id = survey.getKey().getId(); String type = (String) survey.getProperty("projectType"); String name = (String) survey.getProperty("name"); if ("PROJECT".contentEquals(type)) { surveys.add(id); nameOfSurvey.put(id, name); } } }
Source:
public MachineStateDescriptor createMachineFromRecipe(final RecipeMachineCreationMetadata machineFromRecipeMetadata) throws ServerException, ForbiddenException, NotFoundException { requiredNotNull(machineFromRecipeMetadata, "Machine description"); requiredNotNull(machineFromRecipeMetadata.getType(), "Machine type"); requiredNotNull(machineFromRecipeMetadata.getWorkspaceId(), "Workspace id"); requiredNotNull(machineFromRecipeMetadata.getMachineRecipe(), "Recipe descriptor"); requiredNotNull(machineFromRecipeMetadata.getMachineRecipe().getScript(), "Recipe script"); requiredNotNull(machineFromRecipeMetadata.getMachineRecipe().getType(), "Recipe type"); checkCurrentUserPermissions(machineFromRecipeMetadata.getWorkspaceId()); final MachineImpl machine = machineManager.create(machineFromRecipeMetadata); return toDescriptor(machine); }

Target:
public MachineStateDescriptor createMachineFromRecipe(final RecipeMachineCreationMetadata machineFromRecipeMetadata) throws ServerException, ForbiddenException, NotFoundException { requiredNotNull(machineFromRecipeMetadata, "Machine description"); requiredNotNull(machineFromRecipeMetadata.getType(), "Machine type"); requiredNotNull(machineFromRecipeMetadata.getWorkspaceId(), "Workspace id"); requiredNotNull(machineFromRecipeMetadata.getRecipe(), "Recipe"); requiredNotNull(machineFromRecipeMetadata.getRecipe().getScript(), "Recipe script"); requiredNotNull(machineFromRecipeMetadata.getRecipe().getType(), "Recipe type"); checkCurrentUserPermissions(machineFromRecipeMetadata.getWorkspaceId()); final MachineImpl machine = machineManager.create(machineFromRecipeMetadata); return toDescriptor(machine); }
Source:
public void testLogEventWithMasking() { System.out.println("Note: the console will show the 'password' content when running this test."); Marker marker = SecureLogging.CONFIDENTIAL; String password = "classified!"; this.loggerLogback.info(marker, "confidential message with password = '{}'", password); verify(this.mockAppender).doAppend(this.captorLoggingEvent.capture()); final LoggingEvent loggingEvent = this.captorLoggingEvent.getValue(); assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); String layoutMessage = this.encoder.getLayout().doLayout(loggingEvent); System.out.println("test(): layoutMessage = " + layoutMessage); assertFalse("formatted log message must not contain any classified information.", layoutMessage.contains(password)); assertTrue("formatted log message must contain the name of its marker.", layoutMessage.contains(marker.getName())); }

Target:
public void testLogEventWithMasking() { Marker marker = SecureLogging.CONFIDENTIAL; String password = "classified!"; LOG.info(marker, "confidential message with password = '{}'", password); final LoggingEvent loggingEvent = getLastLogEvent(); assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); String layoutMessage = this.encoder.getLayout().doLayout(loggingEvent); assertThat(layoutMessage.contains(password)).as("formatted log message contains classified information.").isFalse(); assertThat(layoutMessage.contains(marker.getName())).as("log message contains name of marker.").isTrue(); }
Source:
public void validate() { try { new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException(String.format("URL '%s' is malformed: %s", url, e.getMessage()), e); } if (intervalInSeconds <= 0) { throw new IllegalArgumentException(String.format( "Invalid intervalInSeconds %d. Interval must be greater than 0.", intervalInSeconds)); } if (connectTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid connectTimeout %d. Timeout must be a positive number.", connectTimeout)); } if (readTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid readTimeout %d. Interval must be a positive number.", readTimeout)); } try { if (!Strings.isNullOrEmpty(charsetString)) { Charset.forName(charsetString); } } catch (UnsupportedCharsetException e) { throw new IllegalArgumentException(String.format("Invalid charset string %s.", charsetString)); } try { convertHeadersToMap(requestHeadersString); } catch (Exception e) { throw new IllegalArgumentException(String.format("Could not parse requestHeadersString string due to: '%s'.", e.getMessage())); } }

Target:
public void validate() { try { new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException(String.format("URL '%s' is malformed: %s", url, e.getMessage()), e); } if (intervalInSeconds <= 0) { throw new IllegalArgumentException(String.format( "Invalid intervalInSeconds %d. Interval must be greater than 0.", intervalInSeconds)); } if (connectTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid connectTimeout %d. Timeout must be 0 or a positive number.", connectTimeout)); } if (readTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid readTimeout %d. Timeout must be 0 or a positive number.", readTimeout)); } try { if (!Strings.isNullOrEmpty(charsetString)) { Charset.forName(charsetString); } } catch (UnsupportedCharsetException e) { throw new IllegalArgumentException(String.format("Invalid charset string %s.", charsetString)); } convertHeadersToMap(requestHeadersString); }
Source:
public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, NotGroupMemberException, PrivilegeException, GroupNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException, WrongAttributeValueException, AlreadyMemberException, WrongReferenceAttributeValueException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "removeMember"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Removing of member is not allowed. Group is externally managed."); } getGroupsManagerBl().removeMember(sess, group, member); }

Target:
public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, NotGroupMemberException, PrivilegeException, GroupNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "removeMember"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Removing of member is not allowed. Group is externally managed."); } getGroupsManagerBl().removeMember(sess, group, member); }
Source:
public Variable(final String identifier, final String content, final String description, final IPath path) { fName = identifier; fContent = content; fDescription = (description != null) ? description : ""; fPath = (path != null) ? (path.makeAbsolute()) : new Path(NAME_ROOT_NODE); }

Target:
public Variable(final String identifier, final String content, final String description, final IPath path) { fName = identifier; fContent = content; fDescription = (description != null) ? description : ""; fPath = (path != null) ? (path.makeAbsolute()) : Path.ROOT; }
Source:
private boolean initTrustedService() { List <String> hosts = new ArrayList<String> (); if (getVds().getStatus() != VDSStatus.NonOperational || getVds().getNonOperationalReason() != NonOperationalReason.UNTRUSTED) { return true; } hosts.add(getVds().getHostName()); List<AttestationValue> value = new ArrayList<AttestationValue> (); try { value = AttestationService.getInstance().attestHosts(hosts); } catch (Exception e) { log.errorFormat("Encounter an exception while attesting host's trustworthiness for Host {0}, Error is {1}", hosts, e); } if (value.size() > 0 && value.get(0).getTrustLevel() == AttestationResultEnum.TRUSTED) { return true; } else { setNonOperational(NonOperationalReason.UNTRUSTED, null); return false; } }

Target:
private boolean initTrustedService() { List <String> hosts = new ArrayList<String> (); if (AttestThread.isTrustedVds(getVds().getId())) { return true; } hosts.add(getVds().getHostName()); List<AttestationValue> value = new ArrayList<AttestationValue> (); try { value = AttestationService.getInstance().attestHosts(hosts); } catch (Exception e) { log.errorFormat("Encounter an exception while attesting host's trustworthiness for Host {0}, Error is {1}", hosts, e); } if (value.size() > 0 && value.get(0).getTrustLevel() == AttestationResultEnum.TRUSTED) { return true; } else { setNonOperational(NonOperationalReason.UNTRUSTED, null); return false; } }
Source:
private static boolean isSingleLineSwitchMember(DetailAST ast) { boolean result = false; final DetailAST slist = ast.getNextSibling(); if (slist == null) { result = true; } else { final DetailAST caseBreak = slist.findFirstToken(TokenTypes.LITERAL_BREAK); if (caseBreak != null) { final DetailAST block = slist.getFirstChild(); final boolean atOneLine = isOnSameLine(ast, block); result = atOneLine && isOnSameLine(block, caseBreak); } } return result; }

Target:
private static boolean isSingleLineSwitchMember(DetailAST ast) { return Optional.of(ast) .map(DetailAST::getNextSibling) .map(DetailAST::getLastChild) .map(lastToken -> isOnSameLine(ast, lastToken)) .orElse(true); }
Source:
private static Object getFieldValue(Class<?> clazz, String fieldName) { try { return clazz.getField(fieldName).get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Java 8 or later but field " + clazz.getName() + "#" + fieldName + " is missing"); } }

Target:
private static Object getFieldValue(Class<?> clazz, String fieldName) { try { return clazz.getField(fieldName).get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Java 8 or later but field " + clazz.getName() + "#" + fieldName + " is missing", e); } }
Source:
public void filter(ContainerRequestContext requestContext) throws IOException { Principal principal = httpRequest.getUserPrincipal(); String scheme = requestContext.getUriInfo().getRequestUri().getScheme(); LOG.debug("Method: {}, AuthType: {}, RemoteUser: {}, UserPrincipal: {}, Scheme: {}", httpRequest.getMethod(), httpRequest.getAuthType(), httpRequest.getRemoteUser(), principal, scheme); if (principal == null || !httpRequest.getAuthType().equalsIgnoreCase(KERBEROS_AUTH)) { throw new WebserviceAuthorizationException("Not authorized"); } SecurityContext securityContext = new StreamlineSecurityContext(principal, scheme, KERBEROS_AUTH); LOG.debug("SecuirtyContext {}", securityContext); requestContext.setSecurityContext(securityContext); }

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { Principal principal = httpRequest.getUserPrincipal(); String scheme = requestContext.getUriInfo().getRequestUri().getScheme(); LOG.debug("Method: {}, AuthType: {}, RemoteUser: {}, UserPrincipal: {}, Scheme: {}", httpRequest.getMethod(), httpRequest.getAuthType(), httpRequest.getRemoteUser(), principal, scheme); if (principal == null || !httpRequest.getAuthType().equalsIgnoreCase(KERBEROS_AUTH)) { throw new WebserviceAuthorizationException("Not authorized"); } SecurityContext securityContext = new StreamlineSecurityContext(principal, scheme, KERBEROS_AUTH); LOG.debug("SecurityContext {}", securityContext); requestContext.setSecurityContext(securityContext); }
Source:
private HashMap<String,String> parseVendorNumber(String vendorNumber) throws BadRequestException { HashMap<String, String> map = new HashMap<>(); if (StringUtils.isEmpty(vendorNumber) || !vendorNumber.contains(CUPurapConstants.DASH)) { throw new BadRequestException(); } String generatedVendorHeaderId = vendorNumber.substring(0, vendorNumber.indexOf(CUPurapConstants.DASH)); String vendorDetailNumber = vendorNumber.substring(vendorNumber.indexOf(CUPurapConstants.DASH) + 1); map.put(PurapPropertyConstants.VENDOR_HEADER_GENERATED_ID, generatedVendorHeaderId); map.put(PurapPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, vendorDetailNumber); return map; }

Target:
private HashMap<String,String> parseVendorNumber(String vendorNumber) throws BadRequestException { HashMap<String, String> map = new HashMap<>(); if (StringUtils.isEmpty(vendorNumber) || !vendorNumber.contains(KFSConstants.DASH) || StringUtils.countMatches(vendorNumber, KFSConstants.DASH) > 1) { throw new BadRequestException(); } String generatedVendorHeaderId = StringUtils.substringBeforeLast(vendorNumber, KFSConstants.DASH); String vendorDetailNumber = StringUtils.substringAfterLast(vendorNumber, KFSConstants.DASH); map.put(PurapPropertyConstants.VENDOR_HEADER_GENERATED_ID, generatedVendorHeaderId); map.put(PurapPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, vendorDetailNumber); return map; }
Source:
Buckets<IN, BucketID> createBuckets(int subtaskIndex) throws IOException { return new Buckets<>( basePath, bucketAssigner, bucketFactory, new BulkPartWriter.Factory<>(writerFactory), rollingPolicy, null, subtaskIndex, outputFileConfig); }

Target:
Buckets<IN, BucketID> createBuckets(int subtaskIndex) throws IOException { return new Buckets<>( basePath, bucketAssigner, bucketFactory, new BulkPartWriter.Factory<>(writerFactory), rollingPolicy, bucketLifeCycleListener, subtaskIndex, outputFileConfig); }
Source:
protected void validateAssertion(final SamlAssertionWrapper samlAssertion) throws WSSecurityException { try { validateSubject(samlAssertion.getSaml2()); } catch (final WSSecurityException e) { LOG.error("Unable to validate Assertion ", e); throw e; } }

Target:
protected void validateAssertion(final SamlAssertionWrapper samlAssertion) throws WSSecurityException { validateSubject(samlAssertion.getSaml2()); }
Source:
public Data createSortedData(@NonNull List<Talk> talks) { TreeMap<Room, TreeSet<RangePosition>> map = new TreeMap<>(ROOM_COMPARATOR); Date minTime = null; Date maxTime = null; for (int i = 0, end = talks.size(); i < end; i++) { Talk talk = talks.get(i); Room room = talk.getRoom(); TimeSlot timeSlot = talk.getTimeSlot(); Date startTime = timeSlot.getStart(); Date endTime = timeSlot.getEnd(); if (minTime == null || minTime.compareTo(startTime) > 0) { minTime = startTime; } if (maxTime == null || maxTime.compareTo(endTime) < 0) { maxTime = endTime; } TreeSet<RangePosition> row = map.get(room); RangePosition tp = new RangePosition(startTime, endTime, i); if (row == null) { row = new TreeSet<>(); map.put(room, row); } row.add(tp); } return new Data(talks, map, minTime, maxTime); }

Target:
public Data createSortedData(@NonNull List<Talk> talks) { TreeMap<Room, TreeSet<RangePosition<Date>>> map = new TreeMap<>(ROOM_COMPARATOR); Date minTime = null; Date maxTime = null; for (int i = 0, end = talks.size(); i < end; i++) { Talk talk = talks.get(i); Room room = talk.getRoom(); TimeSlot timeSlot = talk.getTimeSlot(); Date startTime = timeSlot.getStart(); Date endTime = timeSlot.getEnd(); if (minTime == null || minTime.compareTo(startTime) > 0) { minTime = startTime; } if (maxTime == null || maxTime.compareTo(endTime) < 0) { maxTime = endTime; } TreeSet<RangePosition<Date>> row = map.get(room); if (row == null) { row = new TreeSet<>(); map.put(room, row); } row.add(createRangePosition(startTime, endTime, i)); } return new Data(talks, map, minTime, maxTime); }
Source:
public void refreshSelfHealInfo() { log.debug("Refreshing Gluster Self Heal Data"); for (Cluster cluster : getClusterDao().getAll()) { if (supportsGlusterSelfHealMonitoring(cluster)) { try { refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); } } } }

Target:
public void refreshSelfHealInfo() { log.debug("Refreshing Gluster Self Heal Data"); for (Cluster cluster : getClusterDao().getAll()) { if (supportsGlusterSelfHealMonitoring(cluster)) { try { refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); } } } log.debug("Refreshing Gluster Self Heal data is completed"); }
Source:
private static void init(Supplier<Optional<MeterRegistry>> meterRegistrySupplier) { if (meterRegistry.isPresent()) { log.warn("Registry has already been initialized."); return; } meterRegistry = meterRegistrySupplier.get(); }

Target:
private static void init(Supplier<Optional<MeterRegistry>> meterRegistrySupplier) { if (meterRegistry.isPresent()) { throw new IllegalStateException("Registry has already been initialized."); } meterRegistry = meterRegistrySupplier.get(); }
Source:
private void initJni() throws IOException { File jniDir = new File(mDir, "jni"); if (!jniDir.exists()) { return; } if (mNdkProject) { mNativeSources = jniDir; File makefile = new File(jniDir, "Android.mk"); if (makefile.exists()) { Pattern pattern = Pattern.compile("\\s*LOCAL_MODULE\\s*:=\\s*(\\S+)\\s*"); for (String line : Files.readLines(makefile, Charsets.UTF_8)) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { mNativeModuleName = matcher.group(1); if (mNativeLibs != null) { String libName = "lib" + mNativeModuleName + ".so"; ListIterator<File> iterator = mNativeLibs.listIterator(); while (iterator.hasNext()) { File lib = iterator.next(); if (libName.equals(lib.getName())) { iterator.remove(); } } if (mNativeLibs.isEmpty()) { mNativeLibs = null; } } break; } } } } else { mImporter.reportWarning(this, getClassPathFile(), "Project contains a jni directory, but does not have an Eclipse C/C++ " + "nature: malformed NDK project?"); } }

Target:
private void initJni() throws IOException { File jniDir = new File(mDir, "jni"); if (!jniDir.exists()) { return; } if (mNdkProject) { mNativeSources = jniDir; File makefile = new File(jniDir, "Android.mk"); if (makefile.exists()) { Pattern pattern = Pattern.compile("\\s*LOCAL_MODULE\\s*:=\\s*(\\S+)\\s*"); for (String line : Files.readLines(makefile, Charsets.UTF_8)) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { mNativeModuleName = matcher.group(1); if (mNativeLibs != null) { String libName = "lib" + mNativeModuleName + ".so"; ListIterator<File> iterator = mNativeLibs.listIterator(); while (iterator.hasNext()) { File lib = iterator.next(); if (libName.equals(lib.getName())) { iterator.remove(); } } if (mNativeLibs.isEmpty()) { mNativeLibs = null; } } break; } } } } }
Source:
private static Request parse(final InputStream input) throws IOException { boolean eof = true; final Collection<String> head = new LinkedList<>(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Opt<Integer> data = new Opt.Empty<>(); data = RqLive.data(input, data, false); while (data.get() > 0) { eof = false; if (data.get() == '\r') { RqLive.checkLineFeed(input, baos, head.size() + 1); if (baos.size() == 0) { break; } data = new Opt.Single<>(input.read()); final Opt<String> header = RqLive.newHeader(data, baos); if (header.has()) { head.add(header.get()); } data = RqLive.data(input, data, false); continue; } baos.write(RqLive.legalCharacter(data, baos, head.size() + 1)); data = RqLive.data(input, new Opt.Empty<>(), true); } if (eof) { throw new IOException("empty request"); } return new RqOf( () -> head, () -> input ); }

Target:
private static Request parse(final InputStream input) throws IOException { boolean eof = true; final Collection<String> head = new LinkedList<>(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Opt<Integer> data = new Opt.Empty<>(); data = RqLive.data(input, data, false); while (data.get() > 0) { eof = false; if (data.get() == '\r') { RqLive.checkLineFeed(input, baos, head.size() + 1); if (baos.size() == 0) { break; } data = new Opt.Single<>(input.read()); final Opt<String> header = RqLive.newHeader(data, baos); if (header.has()) { head.add(header.get()); } data = RqLive.data(input, data, false); continue; } baos.write(RqLive.legalCharacter(data, baos, head.size() + 1)); data = RqLive.data(input, new Opt.Empty<>(), true); } if (eof) { throw new IOException("empty request"); } return new RequestOf(head, input); }
Source:
public String translate(final DbColumn c) { switch (c.getDbColumnType()) { case BOOLEAN: return "BOOLEAN"; case DOUBLE: return "DOUBLE PRECISION"; case INT: if (c.isAutoInc()) { return "INT4"; } else { return "INT4"; } case LONG: if (c.isAutoInc()) { return "INT8"; } else { return "INT8"; } case STRING: return format("VARCHAR(%s)", c.isSizeSet() ? c.getSize().toString() : properties.getProperty(VARCHAR_SIZE)); case CLOB: return "TEXT"; case BLOB: return "BYTEA"; case JSON: return "JSONB"; default: throw new DatabaseEngineRuntimeException(format( "Mapping not found for '%s'. Please report this error.", c.getDbColumnType() )); } }

Target:
public String translate(final DbColumn c) { switch (c.getDbColumnType()) { case BOOLEAN: return "BOOLEAN"; case DOUBLE: return "DOUBLE PRECISION"; case INT: return "INT4"; case LONG: return "INT8"; case STRING: return format("VARCHAR(%s)", c.isSizeSet() ? c.getSize().toString() : properties.getProperty(VARCHAR_SIZE)); case CLOB: return "TEXT"; case BLOB: return "BYTEA"; case JSON: return "JSONB"; default: throw new DatabaseEngineRuntimeException(format( "Mapping not found for '%s'. Please report this error.", c.getDbColumnType() )); } }
Source:
public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) { List<InterpreterCompletion> candidates = Collections.emptyList(); try { try { candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor)); } catch (SessionNotFoundException e) { LOGGER.warn("Livy session is expired, new session will be created.", sessionInfo.id); synchronized (this) { if (isSessionExpired()) { initLivySession(); } } candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor)); } } catch (LivyException le) { logger.error("Failed to call code completions. Will return empty list of candidates", le); } return candidates; }

Target:
public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) { List<InterpreterCompletion> candidates = Collections.emptyList(); try { candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor)); } catch (SessionNotFoundException e) { LOGGER.warn("Livy session is expired. Will return empty list of candidates.", sessionInfo.id); } catch (LivyException le) { logger.error("Failed to call code completions. Will return empty list of candidates", le); } return candidates; }
Source:
public Response getGroup(int groupId, String format, String requestedFilename, String acceptHeader) { boolean isCsvRequested = StringUtils.contains(acceptHeader, "text/comma-separated-values") || StringUtils.equalsIgnoreCase( "csv", format); if(isCsvRequested && requestedFilename != null && !new FilenameHelper().isValidFileName(requestedFilename)) { return Response.status(Response.Status.BAD_REQUEST).entity("parameter filename should follow this regex pattern: " + FilenameHelper.REGEX_ALLOWED_CHAR).build(); } else if(isCsvRequested) { final String csvContent = classificationService.exportRules(groupId); final String filename = new FilenameHelper().createFilenameForGroupExport(groupId, requestedFilename); return Response.ok() .header("Content-Disposition", "attachment; filename=\""+filename+"\"") .header("Content-Type", "text/comma-separated-values") .entity(csvContent) .build(); } else { return getGroupAsJson(groupId); } }

Target:
public Response getGroup(int groupId, String format, String requestedFilename, String acceptHeader) { boolean isCsvRequested = (acceptHeader != null && acceptHeader.contains("text/comma-separated-values")) || "csv".equalsIgnoreCase(format); if(isCsvRequested && requestedFilename != null && !new FilenameHelper().isValidFileName(requestedFilename)) { return Response.status(Response.Status.BAD_REQUEST).entity("parameter filename should follow this regex pattern: " + FilenameHelper.REGEX_ALLOWED_CHAR).build(); } else if(isCsvRequested) { return getGroupAsCsv(groupId, requestedFilename); } else { return getGroupAsJson(groupId); } }
Source:
public List<IMetric> transform(List<IMetric> metrics) { if (metrics.size() == 0) { return metrics; } Comparator<IMetric> compare = new Comparator<IMetric>() { public int compare(IMetric m1, IMetric m2) { return m1.getName().compareTo(m2.getName()); } }; Collections.sort(metrics,compare); SimpleMetric workingMetric = new SimpleMetric(metrics.get(0)); ArrayList<IMetric> summedMetrics = new ArrayList<IMetric>(); for (int i = 1; i < metrics.size(); i++) { IMetric curMetric = metrics.get(i); if (workingMetric.getName() != curMetric.getName()) { summedMetrics.add(workingMetric); workingMetric = new SimpleMetric(curMetric); } else { workingMetric.setValue(workingMetric.getValue() + curMetric.getValue()); } } return summedMetrics; }

Target:
public List<IMetric> transform(List<IMetric> metrics) { if (metrics.size() == 0) { return metrics; } Comparator<IMetric> compare = new Comparator<IMetric>() { public int compare(IMetric m1, IMetric m2) { return m1.getName().compareTo(m2.getName()); } }; Collections.sort(metrics,compare); ArrayList<IMetric> summedMetrics = new ArrayList<IMetric>(); SimpleMetric workingMetric = new SimpleMetric(metrics.get(0)); summedMetrics.add(workingMetric); for (int i = 1; i < metrics.size(); i++) { IMetric curMetric = metrics.get(i); if (workingMetric.getName() != curMetric.getName()) { workingMetric = new SimpleMetric(curMetric); summedMetrics.add(workingMetric); } else { workingMetric.setValue(workingMetric.getValue() + curMetric.getValue()); } } return summedMetrics; }
Source:
void addTweets() { final List<Tweet> tweets = new ArrayList<Tweet>(); tweets.add(Tweet.newTweet("artem_zin", "Checkout StorIO — modern API for SQLiteDatabase & ContentResolver")); tweets.add(Tweet.newTweet("HackerNews", "It's revolution! Dolphins can write news on HackerNews with our new app!")); tweets.add(Tweet.newTweet("AndroidDevReddit", "Awesome library — StorIO")); tweets.add(Tweet.newTweet("Facebook", "Facebook community in Twitter is more popular than Facebook community in Facebook and Instagram!")); tweets.add(Tweet.newTweet("Google", "Android be together not the same: AOSP, AOSP + Google Apps, Samsung Android")); tweets.add(Tweet.newTweet("Reddit", "Now we can send funny gifs directly into your brain via Oculus Rift app!")); tweets.add(Tweet.newTweet("ElonMusk", "Tesla Model S OTA update with Android Auto 5.2, fixes for memory leaks")); tweets.add(Tweet.newTweet("AndroidWeekly", "Special issue #1: StorIO — forget about SQLiteDatabase, ContentResolver APIs, ORMs suck!")); tweets.add(Tweet.newTweet("Apple", "Yosemite update: fixes for Wifi issues, yosemite-wifi-patch#142")); storIOContentResolver .put() .objects(tweets) .prepare() .asRxFlowable(MISSING) .observeOn(mainThread()) .subscribe(new FlowableSubscriber<PutResults<Tweet>>() { @Override public void onSubscribe(Subscription subscription) { } @Override public void onError(Throwable e) { safeShowShortToast(getActivity(), R.string.tweets_add_error_toast); } @Override public void onNext(PutResults<Tweet> putResults) { } @Override public void onComplete() { } }); }

Target:
void addTweets() { final List<Tweet> tweets = new ArrayList<Tweet>(); tweets.add(Tweet.newTweet("artem_zin", "Checkout StorIO — modern API for SQLiteDatabase & ContentResolver")); tweets.add(Tweet.newTweet("HackerNews", "It's revolution! Dolphins can write news on HackerNews with our new app!")); tweets.add(Tweet.newTweet("AndroidDevReddit", "Awesome library — StorIO")); tweets.add(Tweet.newTweet("Facebook", "Facebook community in Twitter is more popular than Facebook community in Facebook and Instagram!")); tweets.add(Tweet.newTweet("Google", "Android be together not the same: AOSP, AOSP + Google Apps, Samsung Android")); tweets.add(Tweet.newTweet("Reddit", "Now we can send funny gifs directly into your brain via Oculus Rift app!")); tweets.add(Tweet.newTweet("ElonMusk", "Tesla Model S OTA update with Android Auto 5.2, fixes for memory leaks")); tweets.add(Tweet.newTweet("AndroidWeekly", "Special issue #1: StorIO — forget about SQLiteDatabase, ContentResolver APIs, ORMs suck!")); tweets.add(Tweet.newTweet("Apple", "Yosemite update: fixes for Wifi issues, yosemite-wifi-patch#142")); storIOContentResolver .put() .objects(tweets) .prepare() .asRxCompletable() .observeOn(mainThread()) .subscribe( new Action() { @Override public void run() throws Exception { } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { safeShowShortToast(getActivity(), R.string.tweets_add_error_toast); } } ); }
Source:
public Set<ObjectId> getAlreadyAccepted(Repository repo) { if (alreadyAccepted == null) { alreadyAccepted = Sets.newHashSet(); for (final Ref r : repo.getAllRefs().values()) { if (r.getName().startsWith(Constants.R_HEADS) || r.getName().startsWith(Constants.R_TAGS)) { alreadyAccepted.add(r.getObjectId()); } } } return alreadyAccepted; }

Target:
Set<ObjectId> getAlreadyAccepted(Repository repo) { if (alreadyAccepted == null) { alreadyAccepted = Sets.newHashSet(); for (Ref r : repo.getAllRefs().values()) { if (r.getName().startsWith(Constants.R_HEADS) || r.getName().startsWith(Constants.R_TAGS)) { if (r.getObjectId() != null) { alreadyAccepted.add(r.getObjectId()); } } } } return alreadyAccepted; }
Source:
public void makeGraph() { try { File nodeFile = FileSelector.selectFile("Select node file", this, ".node.graph"); File edgeFile = new File(nodeFile.getAbsolutePath().replace(".node", ".edge")); GeneData geneData = GeneData.parseGenes("geneAnnotationsRef"); final long startTime = System.currentTimeMillis(); GraphDataRepository gd = new GraphDataRepository(); gd.addLoadingObserversList(loadingObservers); gd.parseGraph(nodeFile, edgeFile, geneData); graphView = new GraphView(gd, loadingObservers); zoomBarView = new ZoomBarView(getGraphController()); setZoomBarView(zoomBarView.getPanel()); setGraphView(graphView.getPanel()); graphView.getController().init(); KeyController keys = new KeyController(this); graphView.getPanel().addKeyListener(keys); this.setFocusable(true); long loadTime = System.currentTimeMillis() - startTime; System.out.println("Loadtime: " + loadTime); } catch (FileNotFoundException | FileSelectorException exception) { if (confirm("Error!", "Your file was not found. Want to try again?")) { makeGraph(); } } catch (IOException e) { e.printStackTrace(); } }

Target:
public void makeGraph() { try { File nodeFile = FileSelector.selectFile("Select node file", this, ".node.graph"); File edgeFile = new File(nodeFile.getAbsolutePath().replace(".node", ".edge")); GeneData geneData = GeneData.parseGenes("geneAnnotationsRef"); final long startTime = System.currentTimeMillis(); GraphDataRepository gd = new GraphDataRepository(); gd.addLoadingObserversList(loadingObservers); gd.parseGraph(nodeFile, edgeFile, geneData); graphView = new GraphView(gd, loadingObservers); zoomBarView = new ZoomBarView(getGraphController()); findgenesController = new FindgenesController(gd, getGraphController()); findgenesController.setFrame(this); setZoomBarView(zoomBarView.getPanel()); setGraphView(graphView.getPanel()); graphView.getPanel().requestFocus(); graphView.getController().init(); graphView.getPanel().addKeyListener(keys); this.setFocusable(true); long loadTime = System.currentTimeMillis() - startTime; System.out.println("Loadtime: " + loadTime); } catch (FileNotFoundException | FileSelectorException exception) { if (confirm("Error!", "Your file was not found. Want to try again?")) { makeGraph(); } } catch (IOException e) { e.printStackTrace(); } }
Source:
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { ++cumulations; if (!cumulation.isReadable()) { return in; } assertTrue(cumulation.readableBytes() < messageSize); ByteBuf result = alloc.buffer(messageSize); result.writeBytes(cumulation); while (result.isWritable() && in.isReadable()) { result.writeByte(in.readByte()); } cumulation.release(); if (!in.isReadable()) { in.release(); } return result; }

Target:
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { ++cumulations; if (!cumulation.isReadable()) { cumulation.release(); return in; } assertTrue(cumulation.readableBytes() < messageSize); ByteBuf result = alloc.buffer(messageSize); result.writeBytes(cumulation); while (result.isWritable() && in.isReadable()) { result.writeByte(in.readByte()); } cumulation.release(); if (!in.isReadable()) { in.release(); } return result; }
Source:
private static List<RuleSet> findRuleSets() { List<RuleSet> ruleSets = new ArrayList<>(); for (RuleSetProvider ruleSetProvider : ServiceLoader.load(RuleSetProvider.class)) { ruleSets.add(ruleSetProvider.get()); } return ruleSets; }

Target:
private List<RuleSet> findRuleSets() { List<RuleSet> ruleSets = new ArrayList<>(); for (RuleSetProvider ruleSetProvider : ServiceLoader.load(RuleSetProvider.class)) { ruleSets.add(ruleSetProvider.get()); } return ruleSets; }
Source:
public Long getDirectDownloadExpiration() { return config.get("direct_download_expiration", Long.class, 10L*60); }

Target:
public Optional<Long> getDirectDownloadExpiration() { return Optional.of(config.get("direct_download_expiration", Long.class, 10L*60)); }
Source:
public boolean isSecure() { return isPSK() || isRPK() || isX509() || isOSCORE(); }

Target:
public boolean isSecure() { return isPSK() || isRPK() || isX509(); }
Source:
public TDigest(double compression) { if (compression < 10) { compression = 10; } double sizeFudge = 10; if (compression < 30) { sizeFudge += 20; } this.publicCompression = compression; int size = (int) Math.ceil(this.publicCompression + sizeFudge); int bufferSize = 5 * size; double scale = Math.max(1, bufferSize / size - 1); this.compression = Math.sqrt(scale) * publicCompression; size = (int) Math.ceil(this.compression + sizeFudge); weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; activeCentroids = 0; }

Target:
private TDigest(double compression) { checkArgument(compression <= MAX_COMPRESSION_FACTOR, "Compression factor cannot exceed %s", MAX_COMPRESSION_FACTOR); this.publicCompression = max(compression, 10); this.compression = 2 * publicCompression; int bufferSize = 5 * (int) ceil(this.publicCompression + sizeFudge); int size = (int) ceil(this.compression + sizeFudge); weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; activeCentroids = 0; }
Source:
static Path createConfigurationFileInFs(FileSystem fs, String appHome, Map stormConf, YarnConfiguration yarnConf) throws IOException { Path confDst = new Path(fs.getHomeDirectory(), appHome + Path.SEPARATOR + STORM_CONF_PATH_STRING); Path dirDst = confDst.getParent(); if (!fs.exists(dirDst)) fs.mkdirs(dirDst); if (!fs.exists(confDst)) { FSDataOutputStream out = fs.create(confDst); Yaml yaml = new Yaml(); OutputStreamWriter writer = new OutputStreamWriter(out); rmNulls(stormConf); yaml.dump(stormConf, writer); writer.close(); out.close(); } Path yarn_site_xml = new Path(dirDst, "yarn-site.xml"); if (!fs.exists(yarn_site_xml)) { FSDataOutputStream out = fs.create(yarn_site_xml); OutputStreamWriter writer = new OutputStreamWriter(out); yarnConf.writeXml(writer); writer.close(); out.close(); } return dirDst; }

Target:
static Path createConfigurationFileInFs(FileSystem fs, String appHome, Map stormConf, YarnConfiguration yarnConf) throws IOException { Path confDst = new Path(fs.getHomeDirectory(), appHome + Path.SEPARATOR + STORM_CONF_PATH_STRING); Path dirDst = confDst.getParent(); fs.mkdirs(dirDst); FSDataOutputStream out = fs.create(confDst); Yaml yaml = new Yaml(); OutputStreamWriter writer = new OutputStreamWriter(out); rmNulls(stormConf); yaml.dump(stormConf, writer); writer.close(); out.close(); Path yarn_site_xml = new Path(dirDst, "yarn-site.xml"); out = fs.create(yarn_site_xml); writer = new OutputStreamWriter(out); yarnConf.writeXml(writer); writer.close(); out.close(); return dirDst; }