auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public InMemoryMessageExchangeStore(final NetworkConfig config) { if (config == null) { throw new NullPointerException("Configuration must not be null"); } this.config = config; this.tokenProvider = new InMemoryRandomTokenProvider(this.config); LOGGER.log(Level.CONFIG, "using default TokenProvider {0}", InMemoryRandomTokenProvider.class.getName()); LOGGER.log(Level.CONFIG, "using tokens of {0} bytes in length", config.getInt(NetworkConfig.Keys.TOKEN_SIZE_LIMIT)); }

Target:
public InMemoryMessageExchangeStore(final NetworkConfig config) { this(config, new InMemoryRandomTokenProvider(config)); LOGGER.log(Level.CONFIG, "using default TokenProvider {0}", InMemoryRandomTokenProvider.class.getName()); }
Source:
public void loadMaternalAgeNonZero(){ BaseObject data = mock(BaseObject.class); doReturn(data).when(this.doc).getXObject(any(EntityReference.class)); doReturn(AGE_NON_ZERO).when(data).getIntValue(MATERNAL_AGE); doReturn(AGE_ZERO).when(data).getIntValue(PATERNAL_AGE); PatientData<Integer> testData = this.parentalAgeController.load(this.patient); Assert.assertEquals("parentalAge", testData.getName()); Assert.assertTrue(testData.get(MATERNAL_AGE) == 25); Assert.assertNull(testData.get(PATERNAL_AGE)); }

Target:
public void loadMaternalAgeNonZero(){ BaseObject data = mock(BaseObject.class); doReturn(data).when(this.doc).getXObject(any(EntityReference.class)); doReturn(AGE_NON_ZERO).when(data).getIntValue(MATERNAL_AGE); doReturn(AGE_ZERO).when(data).getIntValue(PATERNAL_AGE); PatientData<Integer> testData = this.parentalAgeController.load(this.patient); Assert.assertEquals("parentalAge", testData.getName()); Assert.assertTrue(testData.get(MATERNAL_AGE) == AGE_NON_ZERO); Assert.assertNull(testData.get(PATERNAL_AGE)); }
Source:
public boolean putJobIfAbsent(T job, boolean asFirst) throws InternalErrorException { if(job == null) throw new InternalErrorException("Can't put null job to list of waiting jobs."); jobsAccessLock.lock(); if(runningJobs.contains(job)) return false; if(waitingJobs.contains(job) && !asFirst) { return false; } else { waitingJobs.remove(job); } if(asFirst) { waitingJobs.addFirst(job); } else { waitingJobs.addLast(job); } notEmptyPoolSemaphore.release(); jobsAccessLock.unlock(); return true; }

Target:
public boolean putJobIfAbsent(T job, boolean asFirst) throws InternalErrorException { if(job == null) throw new InternalErrorException("Can't put null job to list of waiting jobs."); try { jobsAccessLock.lock(); if (runningJobs.contains(job)) return false; if (waitingJobs.contains(job)) { if (!asFirst) { return false; } else { waitingJobs.remove(job); } } if (asFirst) { waitingJobs.addFirst(job); } else { waitingJobs.addLast(job); } notEmptyPoolSemaphore.release(); } finally { jobsAccessLock.unlock(); } return true; }
Source:
public int category(Object element) { IResource adapter = (IResource) getAdapter(element, IResource.class); if (adapter != null) { if (adapter instanceof IContainer) { return FOLDERCATEGORY; } if (adapter instanceof IFile) { IFile file = (IFile) adapter; IPath path = new Path(repositoryMapping .getRepoRelativePath(file)); if (leftOnlyPaths.contains(path)) return ADDEDCATEGORY; if (equalContentPaths.contains(path)) return UNCHANGEDCATEGORY; return CHANGEDCATEGORY; } } if (element instanceof PathNodeAdapter) { return DELETEDCATEGORY; } return UNKNOWNCATEGORY; }

Target:
public int category(Object element) { IResource adapter = (IResource) getAdapter(element, IResource.class); if (adapter != null) { if (adapter instanceof IContainer) { return FOLDERCATEGORY; } if (adapter instanceof IFile) { IFile file = (IFile) adapter; IPath path = new Path(repositoryMapping .getRepoRelativePath(file)); if (addedPaths.contains(path)) return ADDEDCATEGORY; if (equalContentPaths.contains(path)) return UNCHANGEDCATEGORY; return CHANGEDCATEGORY; } } if (element instanceof PathNodeAdapter) return DELETEDCATEGORY; return UNKNOWNCATEGORY; }
Source:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { LogWriter logwriter = new LogWriter(logger,delimiter); graphiteWriter.write(logwriter, server, query, results); }

Target:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { graphiteWriter.write(logwriter, server, query, results); }
Source:
@Override protected javax.sql.DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; }

Target:
protected DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; }
Source:
public void uploadFromHome(User user, Process process) { URI after; try { after = serviceManager.getUserService().getHomeDirectory(user); } catch (Exception ioe) { logger.error("Exception uploadFromHome(...)", ioe); Helper.setFehlerMeldung("Aborted upload from home, error", ioe.getMessage()); return; } if (user.isWithMassDownload()) { after = Paths.get(new File(after).getPath(), process.getProject().getTitle()).toUri(); after = Paths.get(new File(after).getPath().replaceAll(" ", "__")).toUri(); URI projectDirectory = after; if (!fileService.fileExist(projectDirectory) && !fileService.isDirectory(fileService.createResource(projectDirectory.toString()))) { List<String> param = new ArrayList<>(); param.add(new File(after).getPath().replaceAll(" ", "__")); Helper.setFehlerMeldung(Helper.getTranslation("MassDownloadProjectCreationError", param)); logger.error("Can not create project directory " + Paths.get(new File(after).getPath().replaceAll(" ", "__")).toUri()); return; } } after = Paths.get(new File(after).getPath(), getEncodedProcessLinkName(process)).toUri(); URI userHome = after; fileService.deleteSymLink((userHome)); }

Target:
public void uploadFromHome(User user, Process process) { URI destination; try { destination = serviceManager.getUserService().getHomeDirectory(user); } catch (Exception ioe) { logger.error("Exception uploadFromHome(...)", ioe); Helper.setFehlerMeldung("Aborted upload from home, error", ioe.getMessage()); return; } if (user.isWithMassDownload()) { destination = Paths.get(new File(destination).getPath(), process.getProject().getTitle()).toUri(); destination = Paths.get(new File(destination).getPath().replaceAll(" ", "__")).toUri(); if (!fileService.fileExist(destination) && !fileService.isDirectory(fileService.createResource(destination.toString()))) { List<String> param = new ArrayList<>(); param.add(new File(destination).getPath().replaceAll(" ", "__")); Helper.setFehlerMeldung(Helper.getTranslation("MassDownloadProjectCreationError", param)); logger.error("Can not create project directory " + Paths.get(new File(destination).getPath().replaceAll(" ", "__")).toUri()); return; } } destination = Paths.get(new File(destination).getPath(), getEncodedProcessLinkName(process)).toUri(); fileService.deleteSymLink((destination)); }
Source:
static String buildColumns(List<HiveColumnHandle> columns) { if (columns == null || columns.isEmpty()) { return EMPTY_STRING; } return Joiner.on(",").join(columns.stream().map(HiveColumnHandle::getName).collect(Collectors.toList())); }

Target:
private static String buildColumns(List<HiveColumnHandle> columns) { if (columns == null || columns.isEmpty()) { return EMPTY_STRING; } return columns.stream().map(HiveColumnHandle::getName).collect(Collectors.joining(",")); }
Source:
public Response addParser(@FormDataParam("parserJar") final InputStream inputStream, @FormDataParam("parserJar") final FormDataContentDisposition contentDispositionHeader, @FormDataParam("parserInfo") final String parserInfoStr, @FormDataParam("schemaFromParserJar") boolean schemaFromParserJar) { LOG.debug("schemaFromParser {}", schemaFromParserJar); try { String jarStoragePath = UUID.randomUUID().toString() + ".jar"; String name = ""; if (contentDispositionHeader != null && contentDispositionHeader.getFileName() != null) { name = contentDispositionHeader.getFileName(); } this.jarStorage.uploadJar(inputStream, jarStoragePath); inputStream.close(); ParserInfo parserInfo = objectMapper.readValue(parserInfoStr, ParserInfo.class); parserInfo.setJarStoragePath(jarStoragePath); parserInfo.setUploadedFileName(name); if (parserInfo.getParserSchema() == null && schemaFromParserJar) { parserInfo.setParserSchema(loadSchemaFromParserJar(jarStoragePath, parserInfo.getClassName())); } ParserInfo result = catalogService.addParserInfo(parserInfo); return WSUtils.respond(CREATED, SUCCESS, parserInfo); } catch (Exception ex) { return WSUtils.respond(INTERNAL_SERVER_ERROR, EXCEPTION, ex.getMessage()); } }

Target:
public Response addParser(@FormDataParam("parserJar") final InputStream inputStream, @FormDataParam("parserJar") final FormDataContentDisposition contentDispositionHeader, @FormDataParam("parserInfo") final String parserInfoStr, @FormDataParam("schemaFromParserJar") boolean schemaFromParserJar) { LOG.debug("schemaFromParser {}", schemaFromParserJar); try { ParserInfo parserInfo = objectMapper.readValue(parserInfoStr, ParserInfo.class); String prefix = StringUtils.isBlank(parserInfo.getName()) ? "parser-" : parserInfo.getName() + "-"; String jarStoragePath = prefix + UUID.randomUUID().toString() + ".jar"; String uploadedPath = this.jarStorage.uploadJar(inputStream, jarStoragePath); inputStream.close(); LOG.debug("Jar file uploaded to {}", uploadedPath); parserInfo.setJarStoragePath(jarStoragePath); Schema schema = loadSchemaFromParserJar(jarStoragePath, parserInfo.getClassName()); if (schema == null) { throw new RuntimeException("Cannot load parser class from uploaded Jar: " + parserInfo.getClassName()); } if (parserInfo.getParserSchema() == null && schemaFromParserJar) { parserInfo.setParserSchema(schema); } ParserInfo result = catalogService.addParserInfo(parserInfo); return WSUtils.respond(CREATED, SUCCESS, result); } catch (Exception ex) { return WSUtils.respond(INTERNAL_SERVER_ERROR, EXCEPTION, ex.getMessage()); } }
Source:
public ResultModel showMissingDiskStore() { Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers((InternalCache) getCache()); List<ColocatedRegionDetails> missingRegions = null; boolean cacheMemberExist = false; if (!dataMembers.isEmpty()) { cacheMemberExist = true; missingRegions = getMissingColocatedRegionList(dataMembers); } DistributedSystemMXBean dsMXBean = ManagementService.getManagementService(getCache()).getDistributedSystemMXBean(); PersistentMemberDetails[] missingDiskStores = dsMXBean.listMissingDiskStores(); return toMissingDiskStoresTabularResult(missingDiskStores, missingRegions, cacheMemberExist); }

Target:
public ResultModel showMissingDiskStore() { Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers((InternalCache) getCache()); List<ColocatedRegionDetails> missingRegions = null; if (!dataMembers.isEmpty()) { missingRegions = getMissingColocatedRegionList(dataMembers); } DistributedSystemMXBean dsMXBean = ManagementService.getManagementService(getCache()).getDistributedSystemMXBean(); PersistentMemberDetails[] missingDiskStores = dsMXBean.listMissingDiskStores(); return toMissingDiskStoresTabularResult(missingDiskStores, missingRegions); }
Source:
@Override public SqlMonotonicity getMonotonicity(SqlOperatorBinding call) { if (getName().equals("/")) { final SqlMonotonicity mono0 = call.getOperandMonotonicity(0); final SqlMonotonicity mono1 = call.getOperandMonotonicity(1); if (mono1 == SqlMonotonicity.CONSTANT) { if (call.isOperandNull(1, true)) { return SqlMonotonicity.CONSTANT; } if (call.isOperandLiteral(1, false)) { switch (call.getOperandLiteralValue(1, BigDecimal.class).signum()) { case -1: return mono0.reverse().unstrict(); case 0: return SqlMonotonicity.CONSTANT; default: return mono0.unstrict(); } } } } return super.getMonotonicity(call); }

Target:
@Override public SqlMonotonicity getMonotonicity(SqlOperatorBinding call) { if (hasNullOperand(call)) { switch (this.kind) { case DIVIDE: return SqlMonotonicity.CONSTANT; } } if (getName().equals("/")) { final SqlMonotonicity mono0 = call.getOperandMonotonicity(0); final SqlMonotonicity mono1 = call.getOperandMonotonicity(1); if (mono1 == SqlMonotonicity.CONSTANT) { if (call.isOperandLiteral(1, false)) { switch (call.getOperandLiteralValue(1, BigDecimal.class).signum()) { case -1: return mono0.reverse().unstrict(); case 0: return SqlMonotonicity.CONSTANT; default: return mono0.unstrict(); } } } } return super.getMonotonicity(call); }
Source:
private static boolean methodInvocationOnThisInstance(MethodInvocationTree methodInvocation) { ExpressionTree expression = methodInvocation.methodSelect(); if (expression.is(Tree.Kind.MEMBER_SELECT)) { expression = ((MemberSelectExpressionTree) expression).expression(); return expression.is(Tree.Kind.IDENTIFIER) && ((IdentifierTree) expression).name().equals("this"); } return expression.is(Tree.Kind.IDENTIFIER); }

Target:
private static boolean methodInvocationOnThisInstance(MethodInvocationTree methodInvocation) { if (methodInvocation.symbol().isStatic()) { return false; } ExpressionTree expression = methodInvocation.methodSelect(); if (expression.is(Tree.Kind.MEMBER_SELECT)) { expression = ((MemberSelectExpressionTree) expression).expression(); return expression.is(Tree.Kind.IDENTIFIER) && ((IdentifierTree) expression).name().equals("this"); } return expression.is(Tree.Kind.IDENTIFIER); }
Source:
private static H2ODrm zip(final Frame fra, final Vec keysa, final Frame frb, final Vec keysb) { Vec vecs[] = new Vec[fra.vecs().length + frb.vecs().length]; int d = 0; for (Vec vfra : fra.vecs()) vecs[d++] = vfra; for (Vec vfrb : frb.vecs()) vecs[d++] = vfrb; Frame fr = new Frame(vecs); return new H2ODrm(fr, keysa); }

Target:
private static H2ODrm zip(final Frame fra, final Vec keysa, final Frame frb, final Vec keysb) { Vec vecs[] = new Vec[fra.vecs().length + frb.vecs().length]; int d = 0; for (Vec vfra : fra.vecs()) { vecs[d++] = vfra; } for (Vec vfrb : frb.vecs()) { vecs[d++] = vfrb; } Frame fr = new Frame(vecs); return new H2ODrm(fr, keysa); }
Source:
private static List<Integer> extractIntegerList(Map<String, Object> xmlRpcStruct, String propertyName) { if (!xmlRpcStruct.containsKey(propertyName)){ return Collections.emptyList(); } Object[] items = (Object[]) xmlRpcStruct.get(propertyName); if (items.length == 0) { return Collections.emptyList(); } List<Integer> list = new ArrayList<>(); Arrays.stream(items).forEach(item -> list.add((Integer) item)); return list; }

Target:
private static List<Integer> extractIntegerList(Map<String, Object> xmlRpcStruct, String propertyName) { if (!xmlRpcStruct.containsKey(propertyName)){ return Collections.emptyList(); } Object[] items = (Object[]) xmlRpcStruct.get(propertyName); if (items.length == 0) { return Collections.emptyList(); } return Arrays.stream(items).map(item -> (Integer) item).collect(Collectors.toList()); }
Source:
public Schedule(final DataloadProcess process, final String executable, final Schedule triggerSchedule) { notNull(process, "process"); this.type = MSETL_TYPE; this.state = ScheduleState.ENABLED.name(); this.params = new HashMap<>(); this.params.put(PROCESS_ID, process.getId()); process.validateExecutable(executable); this.nextExecutionTime = null; this.consecutiveFailedExecutionCount = 0; this.params.put(EXECUTABLE, executable); this.triggerScheduleId = notEmpty(triggerSchedule.getId(), "trigger schedule ID cannot be null!"); this.links = Collections.emptyMap(); }

Target:
public Schedule(final DataloadProcess process, final String executable, final Schedule triggerSchedule) { this(process, executable); this.triggerScheduleId = notEmpty(notNull(triggerSchedule, "triggerSchedule").getId(), "triggerSchedule ID"); }
Source:
public static Date parseDate(final String date) { final String trimmedDate = date.replaceAll(";.*$",""); ParsePosition pp = new ParsePosition(0); SimpleDateFormat dateFormat = RFC1123_PATTERN_FORMAT.get(); Date val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(RFC1036_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(ASCITIME_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } return null; }

Target:
public static Date parseDate(final String date) { final int semicolonIndex = date.indexOf(';'); final String trimmedDate = semicolonIndex >=0 ? date.substring(0, semicolonIndex) : date; ParsePosition pp = new ParsePosition(0); SimpleDateFormat dateFormat = RFC1123_PATTERN_FORMAT.get(); Date val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(RFC1036_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(ASCITIME_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } return null; }
Source:
private void updateSyncRefreshRate(RefreshTimerTriggeredEvent e) { ApiQuotaInfo info = e.getApiQuotaInfo(); if (remainingApiRequests == UNINITIALIZED){ remainingApiRequests = info.getRemainingRequests(); return; } apiCallsUsedInPreviousRefresh = computeApiCallsUsedInPreviousRefresh(info.getRemainingRequests()); remainingApiRequests = info.getRemainingRequests(); refreshDurationInMinutes = computeRefreshTimerPeriod(info.getRemainingRequests(), Utility.minutesFromNow(info.getNextRefreshInMillisecs()), apiCallsUsedInPreviousRefresh, API_QUOTA_BUFFER, DEFAULT_REFRESH_PERIOD_IN_MINS); this.refreshTimer.restartTimer((int) Utility.minsToSecs(refreshDurationInMinutes)); logger.info("Refresh period updated to " + refreshDurationInMinutes + "mins with API calls used in previous refresh cycle is " + apiCallsUsedInPreviousRefresh + ", current API quota is " + info.getRemainingRequests() + " and next API quota top-up in " + info.getNextRefreshInMinutesFromNow() + "mins."); }

Target:
private void updateSyncRefreshRate(RefreshTimerTriggeredEvent e) { updateSyncRefreshRate(e.getApiQuotaInfo().getRemainingQuota(), e.getApiQuotaInfo().minutesToNextQuotaTopup()); }
Source:
public String search(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam MultiValueMap<String, String> params) throws IOException { CommonParams commonParams = modelCommonParams(request, model, site, params); String queryString = params.getFirst("q"); ArticleSearchQuery.Builder query = ArticleSearchQuery.builder() .setQuery(queryString) .setSimple(commonParams.isSimpleSearch(queryString)); commonParams.fill(query); ArticleSearchQuery queryObj = query.build(); Map<?, ?> searchResults; try { searchResults = solrSearchService.search(queryObj); } catch (ServiceRequestException sre) { return handleInvalidSolrResponse(model, site, queryString, sre); } model.addAttribute("searchResults", solrSearchService.addArticleLinks(searchResults, request, site, siteSet)); Set<SearchFilterItem> activeFilterItems; if ((Double) searchResults.get("numFound") == 0.0) { activeFilterItems = commonParams.setActiveFilterParams(model, request); } else { Map<String, SearchFilter> filters = searchFilterService.getSearchFilters(queryObj, rebuildUrlParameters(queryObj)); filters.values().forEach(commonParams::setActiveAndInactiveFilterItems); activeFilterItems = new LinkedHashSet<>(); filters.values().forEach(filter -> activeFilterItems.addAll(filter.getActiveFilterItems())); model.addAttribute("searchFilters", filters); } model.addAttribute("activeFilterItems", activeFilterItems); return site.getKey() + "/ftl/search/searchResults"; }

Target:
public String search(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam MultiValueMap<String, String> params) throws IOException { CommonParams commonParams = modelCommonParams(request, model, site, params); String queryString = params.getFirst("q"); ArticleSearchQuery.Builder query = ArticleSearchQuery.builder() .setQuery(queryString) .setSimple(commonParams.isSimpleSearch(queryString)); commonParams.fill(query); ArticleSearchQuery queryObj = query.build(); Map<?, ?> searchResults; try { searchResults = solrSearchService.search(queryObj); } catch (ServiceRequestException sre) { return handleFailedSolrRequest(model, site, queryString, sre); } model.addAttribute("searchResults", solrSearchService.addArticleLinks(searchResults, request, site, siteSet)); Set<SearchFilterItem> activeFilterItems; if ((Double) searchResults.get("numFound") == 0.0) { activeFilterItems = commonParams.setActiveFilterParams(model, request); } else { Map<String, SearchFilter> filters = searchFilterService.getSearchFilters(queryObj, rebuildUrlParameters(queryObj)); filters.values().forEach(commonParams::setActiveAndInactiveFilterItems); activeFilterItems = new LinkedHashSet<>(); filters.values().forEach(filter -> activeFilterItems.addAll(filter.getActiveFilterItems())); model.addAttribute("searchFilters", filters); } model.addAttribute("activeFilterItems", activeFilterItems); return site.getKey() + "/ftl/search/searchResults"; }
Source:
public void setMinimumDelay(int delay) { if (delay < CONFIG_MIN_MINIMUM_DELAY) { logger.warn( "Minimum Delay of below minimum permitted, used.", minimumDelay, CONFIG_MIN_MINIMUM_DELAY); minimumDelay = CONFIG_MIN_MINIMUM_DELAY; } this.minimumDelay = delay; }

Target:
public void setMinimumDelay(int delay) { if (delay < CONFIG_MIN_MINIMUM_DELAY) { logger.warn( "Minimum Delay of below minimum permitted, used.", minimumDelay, CONFIG_MIN_MINIMUM_DELAY); delay = CONFIG_MIN_MINIMUM_DELAY; } this.minimumDelay = delay; }
Source:
public static String extractSSNIdentifier(PRPAMT201306UV02ParameterList params) { LOG.trace("Entering HL7DbParser201305.ExtractSSNIdentifier method..."); String ssn = null; if (CollectionUtils.isNotEmpty(params.getLivingSubjectId()) && params.getLivingSubjectId().get(0) != null) { for (PRPAMT201306UV02LivingSubjectId livingSubjectId : params.getLivingSubjectId()) { if (CollectionUtils.isNotEmpty(livingSubjectId.getValue()) && livingSubjectId.getValue().get(0) != null) { II subjectId = livingSubjectId.getValue().get(0); if (subjectId.getExtension() != null && subjectId.getExtension().length() > 0 && subjectId.getRoot() != null && subjectId.getRoot().length() > 0) { if (subjectId.getRoot().equals(SSN_ROOT_IDENTIFIER)) { Identifier ssnId = new Identifier(); ssnId.setId(subjectId.getExtension()); ssnId.setOrganizationId(subjectId.getRoot()); LOG.info("Created id from ssn identifier [organization=", ssnId.getOrganizationId() + "][id=" + ssnId.getId() + "]"); ssn = ssnId.getId(); } } else { LOG.info("message does not contain an id"); } } else { LOG.info("message does not contain an id"); } } } else { LOG.info("message does not contain an id"); } LOG.trace("Exiting HL7DbParser201305.ExtractSSNIdentifier method..."); return ssn; }

Target:
public static String extractSSNIdentifier(PRPAMT201306UV02ParameterList params) { LOG.trace("Entering HL7DbParser201305.ExtractSSNIdentifier method..."); String ssn = null; if (CollectionUtils.isNotEmpty(params.getLivingSubjectId()) && params.getLivingSubjectId().get(0) != null) { for (PRPAMT201306UV02LivingSubjectId livingSubjectId : params.getLivingSubjectId()) { if (CollectionUtils.isNotEmpty(livingSubjectId.getValue()) && livingSubjectId.getValue().get(0) != null) { II subjectId = livingSubjectId.getValue().get(0); if (subjectId.getExtension() != null && subjectId.getExtension().length() > 0 && subjectId.getRoot() != null && subjectId.getRoot().length() > 0) { if (subjectId.getRoot().equals(SSN_ROOT_IDENTIFIER)) { Identifier ssnId = new Identifier(); ssnId.setId(subjectId.getExtension()); ssnId.setOrganizationId(subjectId.getRoot()); LOG.info("Created id from ssn identifier [organization : {}][id : {}] ", ssnId.getOrganizationId(), ssnId.getId()); ssn = ssnId.getId(); } } else { LOG.info("message does not contain an id"); } } else { LOG.info("message does not contain an id"); } } } else { LOG.info("message does not contain an id"); } LOG.trace("Exiting HL7DbParser201305.ExtractSSNIdentifier method..."); return ssn; }
Source:
public static Object getMaxValueForType(FieldType type) { switch (type) { case INTEGER: { return Long.MAX_VALUE; } break; case REAL: { return Double.MAX_VALUE; } break; case DECIMAL: { return BigDecimal.valueOf(Double.MAX_VALUE); } break; case STRING: { return maxStringValue; } break; default: throw new Exception("Invalid field type for index field."); break; } }

Target:
public static Object getMaxValueForType(FieldType type) throws Exception { switch (type) { case INTEGER: { return Long.MAX_VALUE; } case BOOLEAN: { return true; } case REAL: { return Double.MAX_VALUE; } case DECIMAL: { return BigDecimal.valueOf(Double.MAX_VALUE); } case STRING: { return maxStringValue; } default: throw new Exception("Invalid field type for index field."); } }
Source:
public void isEmpty_acrossLinkingObjectListLink() { createIsEmptyDataSet(realm); assertEquals(2, realm.where(AllJavaTypes.class).findAll().size()); for (RealmFieldType type : SUPPORTED_IS_EMPTY_TYPES) { switch (type) { case STRING: assertEquals(0, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_STRING).count()); break; case BINARY: assertEquals(0, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_BINARY).count()); break; case LIST: assertEquals(1, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LIST).count()); break; case LINKING_OBJECTS: assertEquals(1, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_OBJECT).count()); assertEquals(1, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_LIST).count()); break; default: fail("Unknown type: " + type); } } }

Target:
public void isEmpty_acrossLinkingObjectListLink() { createIsEmptyDataSet(realm); assertEquals(3, realm.where(AllJavaTypes.class).findAll().size()); for (RealmFieldType type : SUPPORTED_IS_EMPTY_TYPES) { switch (type) { case STRING: assertEquals(1, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_STRING).count()); break; case BINARY: assertEquals(1, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_BINARY).count()); break; case LIST: assertEquals(1, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LIST).count()); break; case LINKING_OBJECTS: assertEquals(2, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_OBJECT).count()); assertEquals(2, realm.where(AllJavaTypes.class).isEmpty(AllJavaTypes.FIELD_LO_LIST + "." + AllJavaTypes.FIELD_LO_LIST).count()); break; default: fail("Unknown type: " + type); } } }
Source:
void calculateDoubleHitProbability() { final List<Unit> attackingOrderOfLoss = new ArrayList<>(); attackingOrderOfLoss.add(new Unit(INFANTRY, BRITISH, data)); attackingOrderOfLoss.add(new Unit(ARMOUR, BRITISH, data)); final int diceSides = data.getDiceSides(); final Map<Integer, Integer> diceGrouped = getDiceGrouped(attackingOrderOfLoss, List.of()); final StepUnits attackingUnits = new StepUnits(attackingOrderOfLoss, BRITISH, List.of(), GERMAN); final BattleStep root = new BattleStep(attackingUnits, BRITISH, 0, createParameters()); final List<Double> hitProbability = root.calculateHitProbabilities(BattleStep.RollData.of(2, diceGrouped, diceSides)); assertEquals(0.4166, hitProbability.get(0), 0.0001); assertEquals(0.5, hitProbability.get(1), 0.0001); assertEquals(0.0833, hitProbability.get(2), 0.0001); }

Target:
void calculateDoubleHitProbability() { final List<Unit> attackingOrderOfLoss = new ArrayList<>(); attackingOrderOfLoss.add(INFANTRY.create(BRITISH)); attackingOrderOfLoss.add(ARMOUR.create(BRITISH)); final int diceSides = data.getDiceSides(); final Map<Integer, Integer> diceGrouped = getDiceGrouped(attackingOrderOfLoss, List.of()); final StepUnits attackingUnits = new StepUnits(attackingOrderOfLoss, BRITISH, List.of(), GERMAN); final BattleStep root = new BattleStep(attackingUnits, BRITISH, 0, createLandParameters()); final List<Double> hitProbability = root.calculateHitProbabilities(BattleStep.RollData.of(2, diceGrouped, diceSides)); final BinomialDistribution infantryDistribution = new BinomialDistribution(null, 1, 1.0 / 6.0); final BinomialDistribution armourDistribution = new BinomialDistribution(null, 1, 3.0 / 6.0); assertEquals( infantryDistribution.probability(0) * armourDistribution.probability(0), hitProbability.get(0), 0.0001); assertEquals( infantryDistribution.probability(1) * armourDistribution.probability(0) + infantryDistribution.probability(0) * armourDistribution.probability(0), hitProbability.get(1), 0.0001); assertEquals( infantryDistribution.probability(1) * armourDistribution.probability(1), hitProbability.get(2), 0.0001); }
Source:
public void testAbfsOutputStreamDurationTrackerPutRequest() throws IOException { describe("Testing to check if DurationTracker for PUT request is working " + "correctly."); AzureBlobFileSystem fs = getFileSystem(); Path pathForPutRequest = path(getMethodName()); try(AbfsOutputStream outputStream = createAbfsOutputStreamWithFlushEnabled(fs, pathForPutRequest)) { outputStream.write('a'); outputStream.hflush(); AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outputStream); Assertions.assertThat(abfsOutputStreamStatistics.getTimeSpentOnPutRequest()) .describedAs("Mismatch in timeTakenForPutRequest DurationTracker") .isGreaterThan(0.0); } }

Target:
public void testAbfsOutputStreamDurationTrackerPutRequest() throws IOException { describe("Testing to check if DurationTracker for PUT request is working " + "correctly."); AzureBlobFileSystem fs = getFileSystem(); Path pathForPutRequest = path(getMethodName()); try(AbfsOutputStream outputStream = createAbfsOutputStreamWithFlushEnabled(fs, pathForPutRequest)) { outputStream.write('a'); outputStream.hflush(); AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outputStream); Assertions.assertThat(abfsOutputStreamStatistics.getTimeSpentOnPutRequest()) .describedAs("Mismatch in timeSpentOnPutRequest DurationTracker") .isGreaterThan(0.0); } }
Source:
public void run() { try (SweepLocks locks = createSweepLocks()) { waitUntilSpecificTableSweeperIsInitialized(); Thread.sleep(getBackoffTimeWhenSweepHasNotRun()); log.info("Starting background sweeper."); while (true) { if (Thread.currentThread().isInterrupted()) { break; } SweepOutcome outcome = checkConfigAndRunSweep(locks); log.info("Sweep iteration finished with outcome: {}", SafeArg.of("sweepOutcome", outcome)); updateBatchSize(outcome); updateMetrics(outcome); sleepUntilNextRun(outcome); } } catch (InterruptedException e) { log.warn("Shutting down background sweeper. Please restart the service to rerun background sweep."); sweepOutcomeMetrics.registerOccurrenceOf(SweepOutcome.SHUTDOWN); } catch (Throwable t) { log.error("BackgroundSweeper failed fatally and will not rerun until restarted: {}", UnsafeArg.of("message", t.getMessage()), t); sweepOutcomeMetrics.registerOccurrenceOf(SweepOutcome.FATAL); } }

Target:
public void run() { try (SweepLocks locks = createSweepLocks()) { waitUntilSpecificTableSweeperIsInitialized(); Thread.sleep(getBackoffTimeWhenSweepHasNotRun()); log.info("Starting background sweeper."); while (true) { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException("The background sweeper thread is interrupted."); } SweepOutcome outcome = checkConfigAndRunSweep(locks); log.info("Sweep iteration finished with outcome: {}", SafeArg.of("sweepOutcome", outcome)); updateBatchSize(outcome); updateMetrics(outcome); sleepUntilNextRun(outcome); } } catch (InterruptedException e) { log.warn("Shutting down background sweeper. Please restart the service to rerun background sweep."); sweepOutcomeMetrics.registerOccurrenceOf(SweepOutcome.SHUTDOWN); } catch (Throwable t) { log.error("BackgroundSweeper failed fatally and will not rerun until restarted: {}", UnsafeArg.of("message", t.getMessage()), t); sweepOutcomeMetrics.registerOccurrenceOf(SweepOutcome.FATAL); } }
Source:
private void sleepGroup(GroupInfo group, JobInfo info) { Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (isNeverDisplaying(info.getJob(), listener.showsDebug())) continue; if (listener.showsDebug() || group.isActive()) listener.refreshGroup(group); else listener.removeGroup(group); } }

Target:
private void sleepGroup(GroupInfo group, JobInfo info) { for (Object element : listeners.getListeners()) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (isNeverDisplaying(info.getJob(), listener.showsDebug())) continue; if (listener.showsDebug() || group.isActive()) listener.refreshGroup(group); else listener.removeGroup(group); } }
Source:
private void assertSingleAccessibleListener() throws Exception { PlatformUI.getWorkbench().getDisplay().asyncExec(() -> { try { assertEquals(1, getAccessibleListenersSize(getToolBar(animationItem).getAccessible())); } catch (Exception e) { throw new RuntimeException(e); } }); Display display = Display.getCurrent(); while (display.readAndDispatch()) { } }

Target:
private void assertSingleAccessibleListener() throws Exception { Display display = PlatformUI.getWorkbench().getDisplay(); display.asyncExec(() -> { try { assertEquals(1, getAccessibleListenersSize(getToolBar(animationItem).getAccessible())); } catch (Exception e) { throw new RuntimeException(e); } }); while (display.readAndDispatch()) { } }
Source:
BlobStoreCompactor(String dataDir, String storeId, StoreKeyFactory storeKeyFactory, StoreConfig config, StoreMetrics srcMetrics, StoreMetrics tgtMetrics, DiskIOScheduler diskIOScheduler, DiskSpaceAllocator diskSpaceAllocator, Log srcLog, Time time, UUID sessionId, UUID incarnationId) throws IOException, StoreException { this.dataDir = new File(dataDir); this.storeId = storeId; this.storeKeyFactory = storeKeyFactory; this.config = config; this.srcMetrics = srcMetrics; this.tgtMetrics = tgtMetrics; this.srcLog = srcLog; this.diskIOScheduler = diskIOScheduler; this.diskSpaceAllocator = diskSpaceAllocator; this.time = time; this.sessionId = sessionId; this.incarnationId = incarnationId; this.useDirectIO = Utils.isLinux() && config.storeCompactionEnableDirectIO; IndexSegmentValidEntryFilter filter; if (config.storeCompactionFilter.equals(IndexSegmentValidEntryFilterWithoutUndelete.class.getSimpleName())) { filter = new IndexSegmentValidEntryFilterWithoutUndelete(); } else { filter = new IndexSegmentValidEntryFilterWithUndelete(); } validEntryFilter = filter; fixStateIfRequired(); logger.trace("Constructed BlobStoreCompactor for {}", dataDir); }

Target:
BlobStoreCompactor(String dataDir, String storeId, StoreKeyFactory storeKeyFactory, StoreConfig config, StoreMetrics srcMetrics, StoreMetrics tgtMetrics, DiskIOScheduler diskIOScheduler, DiskSpaceAllocator diskSpaceAllocator, Log srcLog, Time time, UUID sessionId, UUID incarnationId) throws IOException, StoreException { this.dataDir = new File(dataDir); this.storeId = storeId; this.storeKeyFactory = storeKeyFactory; this.config = config; this.srcMetrics = srcMetrics; this.tgtMetrics = tgtMetrics; this.srcLog = srcLog; this.diskIOScheduler = diskIOScheduler; this.diskSpaceAllocator = diskSpaceAllocator; this.time = time; this.sessionId = sessionId; this.incarnationId = incarnationId; this.useDirectIO = Utils.isLinux() && config.storeCompactionEnableDirectIO; if (config.storeCompactionFilter.equals(IndexSegmentValidEntryFilterWithoutUndelete.class.getSimpleName())) { validEntryFilter = new IndexSegmentValidEntryFilterWithoutUndelete(); } else { validEntryFilter = new IndexSegmentValidEntryFilterWithUndelete(); } fixStateIfRequired(); logger.trace("Constructed BlobStoreCompactor for {}", dataDir); }
Source:
public void testForExisting() { String url = "/v2/identifiers/ss481155011?species=hsapiens&assembly=grch37"; ResponseEntity<List<Variant>> response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<Variant>>() { }); assertEquals(HttpStatus.OK, response.getStatusCode()); List<Variant> variantList = response.getBody(); assertEquals("1", variantList.get(0).getChromosome()); assertEquals("T", variantList.get(0).getAlternate()); assertEquals("A", variantList.get(0).getReference()); assertTrue(variantList.size() > 0); }

Target:
public void testForExisting() { String url = "/v2/identifiers/ss481155011?species=hsapiens&assembly=grch37"; ResponseEntity<List<Variant>> response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<Variant>>() { }); assertEquals(HttpStatus.OK, response.getStatusCode()); List<Variant> variantList = response.getBody(); assertTrue(variantList.size() > 0); assertEquals("1", variantList.get(0).getChromosome()); assertEquals("T", variantList.get(0).getAlternate()); assertEquals("A", variantList.get(0).getReference()); }
Source:
public static Interval umbrellaInterval(Iterable<Interval> intervals) { DateTime minStart = null; DateTime maxEnd = null; for (Interval interval : intervals) { DateTime curStart = interval.getStart(); DateTime curEnd = interval.getEnd(); if (minStart == null || maxEnd == null) { minStart = curStart; maxEnd = curEnd; } if (curStart.isBefore(minStart)) { minStart = curStart; } if (curEnd.isAfter(maxEnd)) { maxEnd = curEnd; } } if (minStart == null || maxEnd == null) { throw new IllegalArgumentException("Empty list of intervals"); } return new Interval(minStart, maxEnd); }

Target:
public static Interval umbrellaInterval(Iterable<Interval> intervals) { ArrayList<DateTime> startDates = Lists.newArrayList(); ArrayList<DateTime> endDates = Lists.newArrayList(); for (Interval interval : intervals) { startDates.add(interval.getStart()); endDates.add(interval.getEnd()); } DateTime minStart = minDateTime(startDates.toArray(new DateTime[]{})); DateTime maxEnd = maxDateTime(endDates.toArray(new DateTime[]{})); if (minStart == null || maxEnd == null) { throw new IllegalArgumentException("Empty list of intervals"); } return new Interval(minStart, maxEnd); }
Source:
public PageFileFooterOutput(List<Long> stripeOffsets) { this.stripeOffsets = ImmutableList.copyOf(requireNonNull(stripeOffsets, "stripeOffsets is null")); checkArgument(!stripeOffsets.isEmpty(), "stripeOffsets should at least contain offset 0"); }

Target:
public PageFileFooterOutput(List<Long> stripeOffsets) { this.stripeOffsets = ImmutableList.copyOf(requireNonNull(stripeOffsets, "stripeOffsets is null")); }
Source:
public void define(NewController context) { WebService.NewAction action = context.createAction("add_member") .setDescription("Add a user as a member of an organization.<br>" + "Requires 'Administer System' permission on the specified organization.") .setSince("6.4") .setPost(true) .setHandler(this); action .createParam(PARAM_ORGANIZATION) .setDescription("Organization key") .setRequired(true) .setExampleValue(KEY_ORG_EXAMPLE_001); action .createParam("login") .setDescription("User login") .setRequired(true) .setExampleValue("ray.bradbury"); }

Target:
public void define(NewController context) { WebService.NewAction action = context.createAction("add_member") .setDescription("Add a user as a member of an organization.<br>" + "Requires 'Administer System' permission on the specified organization.") .setSince("6.4") .setPost(true) .setInternal(true) .setHandler(this); action .createParam(PARAM_ORGANIZATION) .setDescription("Organization key") .setRequired(true) .setExampleValue(KEY_ORG_EXAMPLE_001); action .createParam(PARAM_LOGIN) .setDescription("User login") .setRequired(true) .setExampleValue("ray.bradbury"); }
Source:
private boolean isDiscardable() { if (!PostUtils.isPublishable(mPost) && isNewPost()) { return true; } return false; }

Target:
private boolean isDiscardable() { return !PostUtils.isPublishable(mPost) && isNewPost(); }
Source:
void typeParameterExceptionToRuntimeException() { fix().addInputLines( "Test.java", "class Test {", " <T extends RuntimeException> void f(ThrowingRunnable<T> in) {", " try {", " in.run();", " } catch (RuntimeException e) {", " System.out.println(\"foo\");", " }", " }", " interface ThrowingRunnable<T extends Exception> {", " void run() throws T;", " }", "}") .expectUnchanged() .doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH); }

Target:
void typeParameterExceptionToRuntimeException() { fix().addInputLines( "Test.java", "class Test {", " <T extends RuntimeException> void f(ThrowingRunnable<T> in) {", " try {", " in.run();", " } catch (Exception e) {", " System.out.println(\"foo\");", " }", " }", " interface ThrowingRunnable<T extends Exception> {", " void run() throws T;", " }", "}") .addOutputLines( "Test.java", "class Test {", " <T extends RuntimeException> void f(ThrowingRunnable<T> in) {", " try {", " in.run();", " } catch (RuntimeException e) {", " System.out.println(\"foo\");", " }", " }", " interface ThrowingRunnable<T extends Exception> {", " void run() throws T;", " }", "}") .doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH); }
Source:
private void createBinaryAddress(byte[] nodeIdByteArray){ if (nodeIdByteArray.length != 6) { throw new NumberFormatException("Ethernet address has to consist of 6 bytes"); } long l = nodeIdByteArray[0] & 0xFF; for (int i = 1; i < 6; ++i) { l = (l << 8) | (nodeIdByteArray[i] & 0xFF); } _address = l; }

Target:
private void createBinaryAddress(byte[] nodeIdByteArray) { if (nodeIdByteArray.length != 6) { throw new NumberFormatException("Node ID address has to consist of 6 bytes"); } long l = nodeIdByteArray[0] & 0xFF; for (int i = 1; i < 6; ++i) { l = (l << 8) | (nodeIdByteArray[i] & 0xFF); } address = l; }
Source:
public Optional<ConnectorNewTableLayout> getInsertLayout(ConnectorSession session, ConnectorTableHandle tableHandle) { HiveTableHandle hiveTableHandle = (HiveTableHandle) tableHandle; SchemaTableName tableName = hiveTableHandle.getSchemaTableName(); Table table = metastore.getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(tableName)); Optional<HiveBucketHandle> hiveBucketHandle = getHiveBucketHandle(table); if (!hiveBucketHandle.isPresent()) { return Optional.empty(); } if (!bucketWritingEnabled) { throw new PrestoException(NOT_SUPPORTED, "Writing to bucketed Hive table has been temporarily disabled"); } HiveBucketProperty bucketProperty = table.getStorage().getBucketProperty() .orElseThrow(() -> new NoSuchElementException("Bucket property should be set")); if (!bucketProperty.getSortedBy().isEmpty() && !isSortedWritingEnabled(session)) { throw new PrestoException(NOT_SUPPORTED, "Writing to bucketed sorted Hive tables is disabled"); } HivePartitioningHandle partitioningHandle = new HivePartitioningHandle( hiveBucketHandle.get().getBucketCount(), hiveBucketHandle.get().getColumns().stream() .map(HiveColumnHandle::getHiveType) .collect(Collectors.toList())); List<String> partitionColumns = hiveBucketHandle.get().getColumns().stream() .map(HiveColumnHandle::getName) .collect(Collectors.toList()); return Optional.of(new ConnectorNewTableLayout(partitioningHandle, partitionColumns)); }

Target:
public Optional<ConnectorNewTableLayout> getInsertLayout(ConnectorSession session, ConnectorTableHandle tableHandle) { HiveTableHandle hiveTableHandle = (HiveTableHandle) tableHandle; SchemaTableName tableName = hiveTableHandle.getSchemaTableName(); Table table = metastore.getTable(tableName.getSchemaName(), tableName.getTableName()) .orElseThrow(() -> new TableNotFoundException(tableName)); Optional<HiveBucketHandle> hiveBucketHandle = getHiveBucketHandle(table); if (!hiveBucketHandle.isPresent()) { return Optional.empty(); } HiveBucketProperty bucketProperty = table.getStorage().getBucketProperty() .orElseThrow(() -> new NoSuchElementException("Bucket property should be set")); if (!bucketProperty.getSortedBy().isEmpty() && !isSortedWritingEnabled(session)) { throw new PrestoException(NOT_SUPPORTED, "Writing to bucketed sorted Hive tables is disabled"); } HivePartitioningHandle partitioningHandle = new HivePartitioningHandle( hiveBucketHandle.get().getBucketCount(), hiveBucketHandle.get().getColumns().stream() .map(HiveColumnHandle::getHiveType) .collect(Collectors.toList())); List<String> partitionColumns = hiveBucketHandle.get().getColumns().stream() .map(HiveColumnHandle::getName) .collect(Collectors.toList()); return Optional.of(new ConnectorNewTableLayout(partitioningHandle, partitionColumns)); }
Source:
public String createPackage() throws IOException { String packagePath = outputFilePath(); FileOutputStream fileOutputStream = new FileOutputStream(packagePath); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); addResourceToPackage(this.manifest, zipOutputStream); for (Resource artifact : this.artifacts) { addResourceToPackage(artifact, zipOutputStream); } zipOutputStream.closeEntry(); zipOutputStream.close(); fileOutputStream.close(); return packagePath; }

Target:
public String createPackage() throws IOException { String packagePath = outputFilePath(); try (FileOutputStream fileOutputStream = new FileOutputStream(packagePath); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) { addManifest(this.manifest, zipOutputStream); zipOutputStream.putNextEntry(new ZipEntry(this.packageName + File.separator)); for (Resource artifact : this.artifacts) { addArtifact(artifact, zipOutputStream); zipOutputStream.closeEntry(); } } return packagePath; }
Source:
public static boolean validConstant(Object o, Litmus litmus) { if (o == null || o instanceof Boolean || o instanceof BigDecimal || o instanceof NlsString || o instanceof ByteString || o instanceof DateString || o instanceof TimeString || o instanceof TimestampString) { return litmus.succeed(); } else if (o instanceof List) { List list = (List) o; for (Object o1 : list) { if (!validConstant(o1, litmus)) { return litmus.fail("not a constant: {}", o1); } } return litmus.succeed(); } else if (o instanceof Map) { @SuppressWarnings("unchecked") final Map<Object, Object> map = (Map) o; for (Map.Entry entry : map.entrySet()) { if (!validConstant(entry.getKey(), litmus)) { return litmus.fail("not a constant: {}", entry.getKey()); } if (!validConstant(entry.getValue(), litmus)) { return litmus.fail("not a constant: {}", entry.getValue()); } } return litmus.succeed(); } else { return litmus.fail("not a constant: {}", o); } }

Target:
public static boolean validConstant(Object o, Litmus litmus) { if (o == null || o instanceof Integer || o instanceof Long || o instanceof Float || o instanceof Double || o instanceof Boolean || o instanceof BigDecimal || o instanceof NlsString || o instanceof ByteString || o instanceof DateString || o instanceof TimeString || o instanceof TimestampString) { return litmus.succeed(); } else if (o instanceof List) { List list = (List) o; for (Object o1 : list) { if (!validConstant(o1, litmus)) { return litmus.fail("not a constant: {}", o1); } } return litmus.succeed(); } else if (o instanceof Map) { @SuppressWarnings("unchecked") final Map<Object, Object> map = (Map) o; for (Map.Entry entry : map.entrySet()) { if (!validConstant(entry.getKey(), litmus)) { return litmus.fail("not a constant: {}", entry.getKey()); } if (!validConstant(entry.getValue(), litmus)) { return litmus.fail("not a constant: {}", entry.getValue()); } } return litmus.succeed(); } else { return litmus.fail("not a constant: {}", o); } }