auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static AuthControlFlag get(String flag) { try { return AuthControlFlag.valueOf(flag.toUpperCase()); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException( String.format("No authorization flag \"%s\", available flags are [%s]. %s", flag, Arrays.asList(AuthControlFlag.values()) .stream() .map(AuthControlFlag::toString) .collect(Collectors.joining(", ")), ex.getLocalizedMessage()), ex); } }

Target:
public static AuthControlFlag get(String flag) throws IllegalArgumentException { try { return AuthControlFlag.valueOf(flag.toUpperCase()); } catch (IllegalArgumentException ex) { throw new IllegalArgumentException( String.format("No control flag \"%s\", available flags are [%s]. %s", flag, Arrays.asList(AuthControlFlag.values()) .stream() .map(AuthControlFlag::toString) .collect(Collectors.joining(", ")), ex.getLocalizedMessage()), ex); } }
Source:
public void reset() { latch = new CountDownLatch(1); latch2 = new CountDownLatch(1); System.out.println("RESET " + latch); }

Target:
public void reset() { latch = new CountDownLatch(1); latch2 = new CountDownLatch(1); }
Source:
public static boolean getEmojiConverter(Context context){ return getBoolean(context, "pref_emoji_converter", false); }

Target:
public static boolean getEmojiConverter(Context context){ return getBoolean(context, "pref_emoji_converter", context.getResources().getBoolean(R.bool.pref_default_emoji_converter)); }
Source:
public void shouldBeConfiguredIfUsernameAndPasswordAreNotNull() throws Exception { boolean isConfigured = usernamePasswordAuthenticationCredentials.isConfigured(); assertThat(isConfigured, is(true)); }

Target:
public void shouldBeConfiguredIfUsernameAndPasswordAreNotNull() { boolean isConfigured = usernamePasswordAuthenticationCredentials.isConfigured(); assertThat(isConfigured, is(true)); }
Source:
public long getRegionSizeInBytes(int positionOffset, int length) { int positionCount = getPositionCount(); if (positionOffset < 0 || length < 0 || positionOffset + length > positionCount) { throw new IndexOutOfBoundsException("Invalid position " + positionOffset + " in block with " + positionCount + " positions"); } return (long) length * (fixedSize + Byte.BYTES); }

Target:
public long getRegionSizeInBytes(int positionOffset, int length) { int positionCount = getPositionCount(); if (positionOffset < 0 || length < 0 || positionOffset + length > positionCount) { throw new IndexOutOfBoundsException("Invalid position " + positionOffset + " in block with " + positionCount + " positions"); } return (fixedSize + Byte.BYTES) * (long) length; }
Source:
public QuotaBalanceVO findLastBalanceEntry(final Long accountId, final Long domainId, final Date beforeThis) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<QuotaBalanceVO>() { @Override public QuotaBalanceVO doInTransaction(final TransactionStatus status) { List<QuotaBalanceVO> quotaBalanceEntries = new ArrayList<>(); Filter filter = new Filter(QuotaBalanceVO.class, "updatedOn", false, 0L, 1L); SearchCriteria<QuotaBalanceVO> sc = createSearchCriteria(); sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); sc.addAnd("creditsId", SearchCriteria.Op.EQ, 0); sc.addAnd("updatedOn", SearchCriteria.Op.LT, beforeThis); quotaBalanceEntries = search(sc, filter); return quotaBalanceEntries.size() > 0 ? quotaBalanceEntries.get(0) : null; } }); }

Target:
public QuotaBalanceVO findLastBalanceEntry(final Long accountId, final Long domainId, final Date beforeThis) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<QuotaBalanceVO>() { @Override public QuotaBalanceVO doInTransaction(final TransactionStatus status) { List<QuotaBalanceVO> quotaBalanceEntries = new ArrayList<>(); Filter filter = new Filter(QuotaBalanceVO.class, "updatedOn", false, 0L, 1L); QueryBuilder<QuotaBalanceVO> qb = QueryBuilder.create(QuotaBalanceVO.class); qb.and(qb.entity().getAccountId(), SearchCriteria.Op.EQ, accountId); qb.and(qb.entity().getDomainId(), SearchCriteria.Op.EQ, domainId); qb.and(qb.entity().getCreditsId(), SearchCriteria.Op.EQ, 0); qb.and(qb.entity().getUpdatedOn(), SearchCriteria.Op.LT, beforeThis); quotaBalanceEntries = search(qb.create(), filter); return !quotaBalanceEntries.isEmpty() ? quotaBalanceEntries.get(0) : null; } }); }
Source:
private void writeObject(ObjectOutputStream out) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (OutputStreamDataOutput osdo = new OutputStreamDataOutput(bos)) { automaton.save(osdo); } byte[] bytes = bos.toByteArray(); out.writeInt(bytes.length); out.write(bytes); }

Target:
private void writeObject(ObjectOutputStream out) throws IOException { automaton.save(new OutputStreamDataOutput(out)); }
Source:
public static Slice ipSubnetMin(@SqlType(StandardTypes.IPPREFIX) Slice value) { validateIpPrefixAndGetBytes(value); return castFromIpPrefixToIpAddress(value); }

Target:
public static Slice ipSubnetMin(@SqlType(StandardTypes.IPPREFIX) Slice value) { return castFromIpPrefixToIpAddress(value); }
Source:
public boolean test(Float value) { return value <= threshold; }

Target:
public boolean test(Float value) { if (value == null) { return threshold < 0; } return value <= threshold; }
Source:
static void throwSuppressed(final String message, final LinkedList<RuntimeException> suppressed) { if (suppressed != null && !suppressed.isEmpty()) { final RuntimeException firstCause = suppressed.pollFirst(); final RuntimeException toThrow = new RuntimeException(message, firstCause); for (final RuntimeException e : suppressed) { toThrow.addSuppressed(e); } throw toThrow; } }

Target:
static void throwSuppressed(final String message, final LinkedList<RuntimeException> suppressed) { if (!suppressed.isEmpty()) { final RuntimeException firstCause = suppressed.pollFirst(); final RuntimeException toThrow = new RuntimeException(message, firstCause); for (final RuntimeException e : suppressed) { toThrow.addSuppressed(e); } throw toThrow; } }
Source:
public void onFullScreen(boolean isFullScreen) { if (isPrepared) { isManualFullscreen = isFullScreen; if (isFullScreen) { enterFullScreen(); } else { exitFullScreen(); } environment.getAnalyticsRegistry().trackVideoOrientation(videoEntry.videoId, player.getCurrentPosition() / AppConstants.MILLISECONDS_PER_SECOND, isFullScreen, videoEntry.eid, videoEntry.lmsUrl, ""); } else { logger.debug("Player not prepared ?? full screen will NOT work!"); } }

Target:
public void onFullScreen(boolean isFullScreen) { if (isPrepared) { isManualFullscreen = isFullScreen; if (isFullScreen) { enterFullScreen(); } else { exitFullScreen(); } environment.getAnalyticsRegistry().trackVideoOrientation(videoEntry.videoId, player.getCurrentPosition() / AppConstants.MILLISECONDS_PER_SECOND, isFullScreen, videoEntry.eid, videoEntry.lmsUrl, null); } else { logger.debug("Player not prepared ?? full screen will NOT work!"); } }
Source:
private String doHttpGet(String urlStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setUseCaches(false); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String theLine; StringBuilder response = new StringBuilder(); while ((theLine = br.readLine()) != null) { response.append(theLine); } connection.disconnect(); return response.toString(); }

Target:
private String doHttpGet(String urlStr) throws IOException { InputStream is=null; StringBuilder response = new StringBuilder(); try{ URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setUseCaches(false); is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String theLine; while ((theLine = br.readLine()) != null) { response.append(theLine); } } finally { if(is!=null){ is.close(); } } return response.toString(); }
Source:
public void userAuthFalseDevIdPermission() throws DeviceAccessAuthorizationException, UserStoreException, PermissionManagementException { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER); Assert.assertFalse(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(3), new String[]{NON_ADMIN_PERMISSION}), "Non admin user accessing not allowed device authorized"); PrivilegedCarbonContext.endTenantFlow(); }

Target:
public void userAuthFalseDevIdPermission() throws DeviceAccessAuthorizationException, UserStoreException, PermissionManagementException { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(NON_ADMIN_ALLOWED_USER); Assert.assertFalse(deviceAccessAuthorizationService.isUserAuthorized(deviceIds.get(3), new String[]{NON_ADMIN_PERMISSION}), "Non admin user accessing not allowed device authorized"); }
Source:
public void setBinaryData(Object binaryuri) { String binaryPath; try { binaryPath = getBinaryPathWithSizeCheck(binaryuri); } catch (IOException e) { e.printStackTrace(); showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); return; } if (binaryPath == null) { if (!destMediaPath.isEmpty()) { new File(destMediaPath).delete(); } return; } File newMedia; if (!destMediaPath.isEmpty()) { newMedia = new File(destMediaPath); } else { recordedFileName = FileUtil.getFileName(binaryPath); String extension = FileUtil.getExtension(binaryPath); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { Toast.makeText(getContext(), Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); Log.e(TAG, String.format( "Could not save file with URI %s because of bad extension %s.", binaryPath, extension )); return; } destMediaPath = mInstanceFolder + System.currentTimeMillis() + customFileTag + "." + extension; File source = new File(binaryPath); newMedia = new File(destMediaPath); try { FileUtil.copyFile(source, newMedia); } catch (IOException e) { showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); e.printStackTrace(); } } try { FileUtil.addMediaToGallery(getContext(), newMedia); showToast("form.attachment.success"); } catch (Exception e) { Log.e(TAG, "Inserting media file FAILED"); e.printStackTrace(); } mBinaryName = newMedia.getName(); }

Target:
public void setBinaryData(Object binaryuri) { String binaryPath; try { binaryPath = getBinaryPathWithSizeCheck(binaryuri); } catch (IOException e) { e.printStackTrace(); showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); return; } if (binaryPath == null) { if (!destMediaPath.isEmpty()) { new File(destMediaPath).delete(); } return; } File newMedia; if (!destMediaPath.isEmpty()) { newMedia = new File(destMediaPath); } else { recordedFileName = FileUtil.getFileName(binaryPath); String extension = FileUtil.getExtension(binaryPath); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { Toast.makeText(getContext(), Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); Log.e(TAG, String.format( "Could not save file with URI %s because of bad extension %s.", binaryPath, extension )); return; } destMediaPath = mInstanceFolder + System.currentTimeMillis() + customFileTag + "." + extension; File source = new File(binaryPath); newMedia = new File(destMediaPath); try { FileUtil.copyFile(source, newMedia); } catch (IOException e) { showToast("form.attachment.copy.fail"); Logger.exception(LogTypes.TYPE_MAINTENANCE, e); e.printStackTrace(); } } if (newMedia.exists()) { showToast("form.attachment.success"); } mBinaryName = newMedia.getName(); }
Source:
public void addExtensions(OpenAPI openAPI) { if (openAPI.getComponents().getSchemas() != null) { schemas = openAPI.getComponents().getSchemas(); if (schemas == null) { schemas = new HashMap<>(); } } for (String name : schemas.keySet()) { Schema schema = schemas.get(name); if (schema.getExtensions() != null) { if (!schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } else { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } if(openAPI.getPaths() != null) { for (String pathname : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathname); resolvePath(pathItem); } } }

Target:
public void addExtensions(OpenAPI openAPI) { if (openAPI.getComponents() != null) { if (openAPI.getComponents().getSchemas() != null) { schemas = openAPI.getComponents().getSchemas(); if (schemas == null) { schemas = new HashMap<>(); } } for (String name : schemas.keySet()) { Schema schema = schemas.get(name); if (schema.getExtensions() != null) { if (!schema.getExtensions().containsKey(Constants.X_SWAGGER_ROUTER_MODEL)) { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } else { schema.addExtension(Constants.X_SWAGGER_ROUTER_MODEL, name); } } } if (openAPI.getPaths() != null) { for (String pathname : openAPI.getPaths().keySet()) { PathItem pathItem = openAPI.getPaths().get(pathname); resolvePath(pathItem); } } }
Source:
public Subscription(TopicName topicName, String name, EndpointAddress endpoint, State state, String description, Object subscriptionPolicy, boolean trackingEnabled, String supportTeam, String contact, ContentType contentType, DeliveryType deliveryType) { this.topicName = topicName; this.name = name; this.endpoint = endpoint; this.state = state; this.description = description; this.trackingEnabled = trackingEnabled; this.supportTeam = supportTeam; this.contact = contact; this.contentType = contentType == null ? ContentType.JSON : contentType; this.deliveryType = deliveryType; this.batchSubscriptionPolicy = this.deliveryType == DeliveryType.BATCH ? (BatchSubscriptionPolicy) subscriptionPolicy : null; this.serialSubscriptionPolicy = this.deliveryType == DeliveryType.SERIAL ? (SubscriptionPolicy) subscriptionPolicy : null; }

Target:
private Subscription(TopicName topicName, String name, EndpointAddress endpoint, State state, String description, Object subscriptionPolicy, boolean trackingEnabled, String supportTeam, String contact, ContentType contentType, DeliveryType deliveryType) { this.topicName = topicName; this.name = name; this.endpoint = endpoint; this.state = state; this.description = description; this.trackingEnabled = trackingEnabled; this.supportTeam = supportTeam; this.contact = contact; this.contentType = contentType == null ? ContentType.JSON : contentType; this.deliveryType = deliveryType; this.batchSubscriptionPolicy = this.deliveryType == DeliveryType.BATCH ? (BatchSubscriptionPolicy) subscriptionPolicy : null; this.serialSubscriptionPolicy = this.deliveryType == DeliveryType.SERIAL ? (SubscriptionPolicy) subscriptionPolicy : null; }
Source:
protected AbstractMetadataResolver getMetadataResolverFromResponse(final HttpResponse response, final File backupFile) throws Exception { if (!HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful()) { if (Files.exists(backupFile.toPath())) { return new InMemoryResourceMetadataResolver(backupFile, this.configBean); } else { throw new Exception("Unable to get entity from MDQ server and a backup file does not exist."); } } val entity = response.getEntity(); val result = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8); val path = backupFile.toPath(); LOGGER.trace("Writing metadata to file at [{}]", path); try (val output = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { IOUtils.write(result, output); output.flush(); output.close(); val etag = response.getFirstHeader("ETag").getValue(); Files.setAttribute(backupFile.toPath(), "user:ETag", ByteBuffer.wrap(etag.getBytes())); } EntityUtils.consume(entity); return new InMemoryResourceMetadataResolver(backupFile, configBean); }

Target:
protected AbstractMetadataResolver getMetadataResolverFromResponse(final HttpResponse response, final File backupFile) throws Exception { if (!HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful()) { if (Files.exists(backupFile.toPath())) { return new InMemoryResourceMetadataResolver(backupFile, this.configBean); } throw new Exception("Unable to get entity from MDQ server and a backup file does not exist."); } val entity = response.getEntity(); val result = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8); val path = backupFile.toPath(); LOGGER.trace("Writing metadata to file at [{}]", path); try (val output = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { IOUtils.write(result, output); output.flush(); val etag = response.getFirstHeader("ETag").getValue(); Files.setAttribute(backupFile.toPath(), "user:ETag", ByteBuffer.wrap(etag.getBytes())); } EntityUtils.consume(entity); return new InMemoryResourceMetadataResolver(backupFile, configBean); }
Source:
public void update(final ViewerCell cell) { if (cell.getElement() instanceof Document) { final Document document = (Document) cell.getElement(); final StyledString styledString = new StyledString(); styledString.append(document.getName()); final String decoration = " -- " + getTypeLabel(document); styledString.append(decoration, StyledString.DECORATIONS_STYLER); styledString.append(" -- ", StyledString.DECORATIONS_STYLER); cell.setText(styledString.getString()); cell.setStyleRanges(styledString.getStyleRanges()); } }

Target:
public void update(final ViewerCell cell) { final Object element = cell.getElement(); if (element instanceof Document) { final Document document = (Document) element; final StyledString styledString = new StyledString(); styledString.append(document.getName()); final String decoration = " -- " + getTypeLabel(document); styledString.append(decoration, StyledString.DECORATIONS_STYLER); styledString.append(" -- ", StyledString.DECORATIONS_STYLER); cell.setText(styledString.getString()); cell.setStyleRanges(styledString.getStyleRanges()); cell.setImage(getImage(element)); } }
Source:
private boolean loopSession() throws IOException { Screen s = getNextScreen(); while (s != null) { try { s.init(mPlatform, mSession, mSandbox); System.out.println("\n\n\n\n\n\n"); s.prompt(System.out); System.out.print("> "); String input = reader.readLine(); if(input.startsWith(":")) { if(input.equals(":exit") || input.equals(":quit")) { System.exit(-1); } if (input.startsWith(":update")) { mUpdatePending = true; if(input.contains("-f")) { mForceLatestUpdate = true; } return true; } if(input.equals(":home")) { return true; } } s.updateSession(mSession, input); s = getNextScreen(); } catch (CommCareSessionException ccse) { System.out.println("Error during session execution:"); ccse.printStackTrace(); System.out.println("Press return to restart the session"); reader.readLine(); return true; } } String formXmlns = mSession.getForm(); XFormPlayer player = new XFormPlayer(System.in, System.out, null); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); return true; }

Target:
private boolean loopSession() throws IOException { Screen s = getNextScreen(); while (s != null) { try { s.init(mPlatform, mSession, mSandbox); System.out.println("\n\n\n\n\n\n"); s.prompt(System.out); System.out.print("> "); String input = reader.readLine(); if(input.startsWith(":")) { if(input.equals(":exit") || input.equals(":quit")) { return false; } if (input.startsWith(":update")) { mUpdatePending = true; if(input.contains("-f")) { mForceLatestUpdate = true; } return true; } if(input.equals(":home")) { return true; } } s.updateSession(mSession, input); s = getNextScreen(); } catch (CommCareSessionException ccse) { System.out.println("Error during session execution:"); ccse.printStackTrace(); System.out.println("Press return to restart the session"); reader.readLine(); return true; } } String formXmlns = mSession.getForm(); XFormPlayer player = new XFormPlayer(System.in, System.out, null); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); return true; }
Source:
private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) { final TwoWayChannelMessage response = initiateCapture.getValue(); final MessageType type = response.getType(); assertEquals("Wrong type " + type, MessageType.INITIATE, type); final long actualExpire = response.getInitiate().getExpireTimeSecs(); long delta = 1; assertTrue("Expiretime to to small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire + delta); assertTrue("Expiretime to to large " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire - delta); }

Target:
private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) { final TwoWayChannelMessage response = initiateCapture.getValue(); final MessageType type = response.getType(); assertEquals("Wrong type " + type, MessageType.INITIATE, type); final long actualExpire = response.getInitiate().getExpireTimeSecs(); assertTrue("Expire time too small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire); assertTrue("Expire time too large " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire); }
Source:
private static PersistenceDescriptor persistenceXml() { return Descriptors.create( PersistenceDescriptor.class ) .version( "2.0" ) .createPersistenceUnit() .name( "primary" ) .provider( "org.hibernate.ogm.jpa.HibernateOgmPersistence" ) .clazz( Member.class.getName() ) .getOrCreateProperties() .createProperty().name( "hibernate.ogm.datastore.provider" ).value( "couchdb" ).up() .createProperty().name( "hibernate.ogm.couchdb.host" ).value( "localhost" ).up() .createProperty().name( "hibernate.ogm.couchdb.port" ).value( "5984" ).up() .createProperty().name( "hibernate.ogm.couchdb.database" ).value( "ogm_test_database" ).up() .createProperty().name( "hibernate.org.couchdb.createdatabase" ).value( "true" ).up() .up().up(); }

Target:
private static PersistenceDescriptor persistenceXml() { return Descriptors.create( PersistenceDescriptor.class ) .version( "2.0" ) .createPersistenceUnit() .name( "primary" ) .provider( "org.hibernate.ogm.jpa.HibernateOgmPersistence" ) .clazz( Member.class.getName() ) .getOrCreateProperties() .createProperty().name( "hibernate.ogm.datastore.provider" ).value( "couchdb" ).up() .createProperty().name( "hibernate.ogm.couchdb.host" ).value( couchDBHostName ).up() .createProperty().name( "hibernate.ogm.couchdb.couchDBPortNumber" ).value( couchDBPortNumber ).up() .createProperty().name( "hibernate.ogm.couchdb.database" ).value( "ogm_test_database" ).up() .createProperty().name( "hibernate.org.couchdb.createdatabase" ).value( "true" ).up() .up().up(); }
Source:
public void channelInactive(ChannelHandlerContext ctx) { try { if (requestHandler != null) { requestHandler.onRequestComplete(request); } if (responseHandler != null) { responseHandler.onRequestComplete(request); } } catch (Exception e) { logger.error("Unable to perform cleanup tasks. Swallowing exception..", e); nettyMetrics.channelInactiveTasksFailureCount.inc(); } }

Target:
public void channelInactive(ChannelHandlerContext ctx) { onRequestComplete(null, true); }
Source:
public void stop() { authzHelper.checkPermission(AuthorizationPermission.LIFECYCLE); startSemaphore.lock(); if (stopSemaphore.tryLock()) { try { log.debugf("Stopping cache manager %s on %s", configurationManager.getGlobalConfiguration().transport().clusterName(), getAddress()); stopCaches(); globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop(); globalComponentRegistry.stop(); } finally { stopSemaphore.unlock(); } } else { log.trace("Ignore call to stop as the cache manager is stopping"); } startSemaphore.unlock(); }

Target:
public void stop() { authzHelper.checkPermission(AuthorizationPermission.LIFECYCLE); startLock.lock(); if (stopLock.tryLock()) { try { log.debugf("Stopping cache manager %s on %s", configurationManager.getGlobalConfiguration().transport().clusterName(), getAddress()); stopCaches(); globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop(); globalComponentRegistry.stop(); } finally { stopLock.unlock(); } } else { log.trace("Ignore call to stop as the cache manager is stopping"); } startLock.unlock(); }
Source:
public ValidationIssueSearchRequestBuilder filterByDetails(Map<String, Object> details) { final Options options = Options.builder().putAll(details).build(); return addOption(OptionKey.DETAILS, options); }

Target:
public ValidationIssueSearchRequestBuilder filterByDetails(Map<String, Object> details) { final Options options = Options.from(details); return addOption(OptionKey.DETAILS, options); }
Source:
public void requestMetadataSetCorrectly() { callRuntimeExceptionEndpoint(); Report report = verifyAndGetReport(); assertEquals("GET /throw-runtime-exception", report.getContext()); @SuppressWarnings(value = "unchecked") Map<String, Object> requestMetadata = (Map<String, Object>) report.getMetaData().get("request"); assertEquals("http://localhost:" + randomServerPort + "/throw-runtime-exception", requestMetadata.get("url")); assertEquals("GET", requestMetadata.get("method")); assertEquals("127.0.0.1", requestMetadata.get("clientIp")); @SuppressWarnings(value = "unchecked") Map<String, String[]> params = (Map<String, String[]>) requestMetadata.get("params"); assertEquals("paramVal1", params.get("param1")[0]); assertEquals("paramVal2", params.get("param2")[0]); @SuppressWarnings(value = "unchecked") Map<String, String> headers = (Map<String, String>) requestMetadata.get("headers"); assertEquals("headerVal1", headers.get("header1")); assertEquals("headerVal2", headers.get("header2")); }

Target:
public void requestMetadataSetCorrectly() { callRuntimeExceptionEndpoint(); Report report = verifyAndGetReport(); assertEquals("GET /throw-runtime-exception", report.getContext()); @SuppressWarnings(value = "unchecked") Map<String, Object> requestMetadata = (Map<String, Object>) report.getMetaData().get("request"); assertEquals("http://localhost:" + randomServerPort + "/throw-runtime-exception", requestMetadata.get("url")); assertEquals("GET", requestMetadata.get("method")); assertEquals("127.0.0.1", requestMetadata.get("clientIp")); @SuppressWarnings(value = "unchecked") Map<String, String[]> params = (Map<String, String[]>) requestMetadata.get("params"); assertEquals("paramVal1", params.get("param1")[0]); assertEquals("paramVal2", params.get("param2")[0]); @SuppressWarnings(value = "unchecked") Map<String, String> headers = (Map<String, String>) requestMetadata.get("headers"); assertEquals("header1Val1,header1Val2", headers.get("header1")); assertEquals("header2Val1", headers.get("header2")); }
Source:
private void fillProjectProperties(final List<ProjectProperty> projectProperties, final SampleDetailsDTO samplesDetailsDto) { for (ProjectProperty projectProperty : projectProperties) { if (projectProperty.getTypeId().equals(8383) && StringUtils.isNotBlank(projectProperty.getValue())) { final String plantingDate = projectProperty.getValue(); samplesDetailsDto.setSeedingDate(plantingDate); } if (projectProperty.getTypeId().equals(8370) && StringUtils.isNotBlank(projectProperty.getValue())) { final String season = projectProperty.getValue(); samplesDetailsDto.setSeason(season); } } }

Target:
private void fillProjectProperties(final List<ProjectProperty> projectProperties, final SampleDetailsDTO samplesDetailsDto) { for (final ProjectProperty projectProperty : projectProperties) { if (projectProperty.getTypeId().equals(TermId.SEEDING_DATE.getId()) && StringUtils.isNotBlank(projectProperty.getValue())) { final String plantingDate = projectProperty.getValue(); samplesDetailsDto.setSeedingDate(plantingDate); } if (projectProperty.getTypeId().equals(TermId.SEASON_VAR_TEXT.getId()) && StringUtils.isNotBlank(projectProperty.getValue())) { final String season = projectProperty.getValue(); samplesDetailsDto.setSeason(season); } } }
Source:
protected synchronized void modified(Map<String, Object> config) { final String language = (String) config.get(LANGUAGE); final String script = (String) config.get(SCRIPT); final String region = (String) config.get(REGION); final String variant = (String) config.get(VARIANT); final String location = (String) config.get(LOCATION); if (location != null) { try { this.location = PointType.valueOf(location); } catch (IllegalArgumentException e) { logger.warn("Could not set new location, keeping old one: ", e.getMessage()); } } if (StringUtils.isEmpty(language)) { logger.debug("No language set, fallback to default system locale"); locale = null; return; } final Locale.Builder builder = new Locale.Builder(); try { builder.setLanguage(language); } catch (final RuntimeException ex) { logger.warn("Language ({}) is invalid. Cannot create locale, keep old one.", language, ex); return; } try { builder.setScript(script); } catch (final RuntimeException ex) { logger.warn("Script ({}) is invalid. Skip it.", script, ex); return; } try { builder.setRegion(region); } catch (final RuntimeException ex) { logger.warn("Region ({}) is invalid. Skip it.", region, ex); return; } try { builder.setVariant(variant); } catch (final RuntimeException ex) { logger.warn("Variant ({}) is invalid. Skip it.", variant, ex); return; } locale = builder.build(); logger.info("Locale set to {}", locale); }

Target:
protected synchronized void modified(Map<String, Object> config) { final String language = (String) config.get(LANGUAGE); final String script = (String) config.get(SCRIPT); final String region = (String) config.get(REGION); final String variant = (String) config.get(VARIANT); final String location = (String) config.get(LOCATION); if (location != null) { try { this.location = PointType.valueOf(location); } catch (IllegalArgumentException e) { logger.warn("Could not set new location, keeping old one: ", e.getMessage()); } } if (StringUtils.isEmpty(language)) { logger.debug("No language set, fallback to default system locale"); locale = null; return; } final Locale.Builder builder = new Locale.Builder(); try { builder.setLanguage(language); } catch (final RuntimeException ex) { logger.warn("Language ({}) is invalid. Cannot create locale, keep old one.", language, ex); return; } try { builder.setScript(script); } catch (final RuntimeException ex) { logger.warn("Script ({}) is invalid. Skip it.", script, ex); return; } try { builder.setRegion(region); } catch (final RuntimeException ex) { logger.warn("Region ({}) is invalid. Skip it.", region, ex); return; } try { builder.setVariant(variant); } catch (final RuntimeException ex) { logger.warn("Variant ({}) is invalid. Skip it.", variant, ex); return; } locale = builder.build(); logger.info("Locale set to {}, Location set to {}", locale, this.location); }
Source:
public static BytecodeExpression invokeFunction(Scope scope, CachedInstanceBinder cachedInstanceBinder, String name, ScalarFunctionImplementation function, List<BytecodeExpression> parameters) { requireNonNull(scope, "scope is null"); requireNonNull(function, "function is null"); CallSiteBinder binder = cachedInstanceBinder.getCallSiteBinder(); Binding binding = cachedInstanceBinder.getCallSiteBinder().bind(function.getMethodHandle()); Optional<BytecodeNode> instance = Optional.empty(); if (function.getInstanceFactory().isPresent()) { FieldDefinition field = cachedInstanceBinder.getCachedInstance(function.getInstanceFactory().get()); instance = Optional.of(scope.getThis().getField(field)); } return new InvokeFunctionBytecodeExpression(scope, binder, name, function, instance, parameters); }

Target:
public static BytecodeExpression invokeFunction(Scope scope, CachedInstanceBinder cachedInstanceBinder, String name, ScalarFunctionImplementation function, List<BytecodeExpression> parameters) { requireNonNull(scope, "scope is null"); requireNonNull(function, "function is null"); Optional<BytecodeNode> instance = Optional.empty(); if (function.getInstanceFactory().isPresent()) { FieldDefinition field = cachedInstanceBinder.getCachedInstance(function.getInstanceFactory().get()); instance = Optional.of(scope.getThis().getField(field)); } return new InvokeFunctionBytecodeExpression(scope, cachedInstanceBinder.getCallSiteBinder(), name, function, instance, parameters); }
Source:
public static @Nonnull JenkinsLocationConfiguration getOrDie(){ JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { throw new IllegalStateException("JenkinsLocationConfiguration instance is missing. Probably the Jenkins instance is fully loaded at that time."); } return config; }

Target:
public static @Nonnull JenkinsLocationConfiguration getOrDie(){ JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); if (config == null) { throw new IllegalStateException("JenkinsLocationConfiguration instance is missing. Probably the Jenkins instance is not fully loaded at this time."); } return config; }
Source:
private void addSessionToken(ResourceId resourceId, String partitionKeyRangeId, ISessionToken parsedSessionToken) { ConcurrentHashMap<String, ISessionToken> existingTokensIfAny = this.collectionResourceIdToSessionTokens.get(resourceId.getUniqueDocumentCollectionId()); if (existingTokensIfAny != null) { ConcurrentHashMap<String, ISessionToken> existingTokens = existingTokensIfAny; existingTokens.merge(partitionKeyRangeId, parsedSessionToken, (existingSessionTokens, newSessionToken) -> { try { if (existingSessionTokens == null) { return newSessionToken; } return existingSessionTokens.merge(newSessionToken); } catch (CosmosClientException e) { throw new IllegalStateException(e); } }); return; } this.collectionResourceIdToSessionTokens.compute( resourceId.getUniqueDocumentCollectionId(), (k, existingTokens) -> { if (existingTokens == null) { logger.info("Registering a new collection resourceId in SessionTokens", resourceId); ConcurrentHashMap<String, ISessionToken> tokens = new ConcurrentHashMap(200, 0.75f, 2000); tokens.put(partitionKeyRangeId, parsedSessionToken); return tokens; } existingTokens.merge(partitionKeyRangeId, parsedSessionToken, (existingSessionTokens, newSessionToken) -> { try { if (existingSessionTokens == null) { return newSessionToken; } return existingSessionTokens.merge(newSessionToken); } catch (CosmosClientException e) { throw new IllegalStateException(e); } }); return existingTokens; }); }

Target:
private void addSessionToken(ResourceId resourceId, String partitionKeyRangeId, ISessionToken parsedSessionToken) { ConcurrentHashMap<String, ISessionToken> existingTokensIfAny = this.collectionResourceIdToSessionTokens.get(resourceId.getUniqueDocumentCollectionId()); if (existingTokensIfAny != null) { updateExistingTokensInternal(existingTokensIfAny, partitionKeyRangeId, parsedSessionToken); return; } this.collectionResourceIdToSessionTokens.compute( resourceId.getUniqueDocumentCollectionId(), (k, existingTokens) -> { if (existingTokens == null) { logger.info("Registering a new collection resourceId in SessionTokens", resourceId); ConcurrentHashMap<String, ISessionToken> tokens = new ConcurrentHashMap(200, 0.75f, 2000); tokens.put(partitionKeyRangeId, parsedSessionToken); return tokens; } updateExistingTokensInternal(existingTokens, partitionKeyRangeId, parsedSessionToken); return existingTokens; }); }
Source:
private void startAutomaticRefresh(MeteoBlueConfiguration config) { if (refreshJob != null && !refreshJob.isCancelled()) { logger.trace("Refresh job already exists."); return; } Runnable runnable = new Runnable() { @Override public void run() { boolean updateSuccessful = false; try { updateSuccessful = updateWeatherData(); if (updateSuccessful) { for (int i = 0; i < 7; i++) { forecasts[i] = new Forecast(i, weatherData.getMetadata(), weatherData.getUnits(), weatherData.getDataDay()); } for (Channel channel : getThing().getChannels()) { updateChannel(channel.getUID().getId()); } } } catch (Exception e) { logger.debug("Exception occurred during weather update: {}", e.getMessage(), e); } } }; int period = config.refresh != null ? config.refresh : MeteoBlueConfiguration.DEFAULT_REFRESH; refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, period, TimeUnit.MINUTES); }

Target:
private void startAutomaticRefresh(MeteoBlueConfiguration config) { if (refreshJob != null && !refreshJob.isCancelled()) { logger.trace("Refresh job already exists."); return; } Runnable runnable = () -> { boolean updateSuccessful = false; try { updateSuccessful = updateWeatherData(); if (updateSuccessful) { for (int i = 0; i < 7; i++) { forecasts[i] = new Forecast(i, weatherData.getMetadata(), weatherData.getUnits(), weatherData.getDataDay()); } for (Channel channel : getThing().getChannels()) { updateChannel(channel.getUID().getId()); } } } catch (Exception e) { logger.warn("Exception occurred during weather update: {}", e.getMessage(), e); } }; int period = config.refresh != null ? config.refresh : MeteoBlueConfiguration.DEFAULT_REFRESH; refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, period, TimeUnit.MINUTES); }
Source:
public void fillContextMenu(IMenuManager aMenu) { IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); if (selection.size() != 1) { return; } Object object = selection.getFirstElement(); if (! (object instanceof IFolder)) { return; } IFolder folder = (IFolder) object; if (folder.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).exists()) { for (IProject project : folder.getWorkspace().getRoot().getProjects()) { if (project.getLocation().equals(folder.getLocation())) { SelectProjectForFolderAction action = new SelectProjectForFolderAction(project, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, action); return; } } OpenFolderAsProjectAction action = new OpenFolderAsProjectAction(folder, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, action); } }

Target:
public void fillContextMenu(IMenuManager aMenu) { IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); if (selection.size() != 1) { return; } Object object = selection.getFirstElement(); IFolder folder = (IFolder)AdaptabilityUtility.getAdapter(object, IFolder.class); if (folder == null) { return; } if (folder.getFile(IProjectDescription.DESCRIPTION_FILE_NAME).exists()) { for (IProject project : folder.getWorkspace().getRoot().getProjects()) { if (project.getLocation().equals(folder.getLocation())) { SelectProjectForFolderAction action = new SelectProjectForFolderAction(project, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, action); return; } } OpenFolderAsProjectAction action = new OpenFolderAsProjectAction(folder, this.viewer); aMenu.insertAfter(ICommonMenuConstants.GROUP_BUILD, action); } }
Source:
protected void copyVmDevices() { getVmDeviceUtils().copyVmDevices(vmDevicesSourceId, getVmId(), getSrcDeviceIdToTargetDeviceIdMapping(), isSoundDeviceEnabled(), getParameters().isConsoleEnabled(), isVirtioScsiEnabled(), isBalloonEnabled(), getParameters().getGraphicsDevices().keySet(), false, getEffectiveCompatibilityVersion()); getVmDeviceUtils().updateUsbSlots(getVmTemplate(), getVm().getStaticData()); if (getInstanceTypeId() != null) { copyDiskDevicesFromTemplate(); } }

Target:
protected void copyVmDevices() { getVmDeviceUtils().copyVmDevices(vmDevicesSourceId, getVmId(), getSrcDeviceIdToTargetDeviceIdMapping(), isSoundDeviceEnabled(), getParameters().isConsoleEnabled(), isVirtioScsiEnabled(), isBalloonEnabled(), getParameters().getGraphicsDevices().keySet(), false, getEffectiveCompatibilityVersion()); if (getVmTemplate().getUsbPolicy() != getVm().getUsbPolicy()) { getVmDeviceUtils().updateUsbSlots(getVmTemplate(), getVm().getStaticData()); } if (getInstanceTypeId() != null) { copyDiskDevicesFromTemplate(); } }
Source:
public ZapSupportPanel() { super(new GridBagLayout(), true); GridBagConstraints gbcSupportDetails = new GridBagConstraints(); JTextArea supportDetailsTextArea = new JTextArea(); supportDetailsTextArea.setEditable(false); StringBuffer supportDetailsBuffer = new StringBuffer(300); supportDetailsBuffer.append(PRODUCT).append(NEWLINE); supportDetailsBuffer.append(VERSION).append(NEWLINE); supportDetailsBuffer.append("---").append(NEWLINE); supportDetailsBuffer.append(WordUtils.wrap(INSTALLED_ADDONS, 60)).append(NEWLINE); supportDetailsBuffer.append("---").append(NEWLINE); supportDetailsBuffer.append(OS).append(NEWLINE); supportDetailsBuffer.append(JAVA_VERSION).append(NEWLINE); supportDetailsBuffer.append(ZAP_HOME).append(NEWLINE); supportDetailsTextArea.setText(supportDetailsBuffer.toString()); gbcSupportDetails.gridx = 3; gbcSupportDetails.gridy = 0; gbcSupportDetails.ipadx = 0; gbcSupportDetails.ipady = 0; gbcSupportDetails.anchor = GridBagConstraints.NORTHWEST; gbcSupportDetails.insets = new Insets(2, 2, 2, 2); this.add(supportDetailsTextArea, gbcSupportDetails); }

Target:
public ZapSupportPanel() { super(new GridBagLayout(), true); GridBagConstraints gbcSupportDetails = new GridBagConstraints(); JTextArea supportDetailsTextArea = new JTextArea(); supportDetailsTextArea.setEditable(false); supportDetailsTextArea.setText(ZapSupportUtils.getAll(true)); gbcSupportDetails.gridx = 3; gbcSupportDetails.gridy = 0; gbcSupportDetails.ipadx = 0; gbcSupportDetails.ipady = 0; gbcSupportDetails.weightx = 1.0D; gbcSupportDetails.weighty = 1.0D; gbcSupportDetails.fill = GridBagConstraints.BOTH; gbcSupportDetails.anchor = GridBagConstraints.NORTHWEST; gbcSupportDetails.insets = new Insets(2, 2, 2, 2); this.add(supportDetailsTextArea, gbcSupportDetails); }
Source:
public float getX() { return this.xCoordinate; }

Target:
public double getX() { return this.xCoordinate; }
Source:
public ReaderOptions(ValidationStringency stringency, boolean includeUnmappedReads) { super(); this.stringency = stringency; this.includeUnmappedReads = includeUnmappedReads; }

Target:
public ReaderOptions(ValidationStringency stringency, boolean includeUnmappedReads) { this.stringency = stringency; this.includeUnmappedReads = includeUnmappedReads; }
Source:
private String getDbVendor() { return dbClient.getDatabase().getDialect().getId().toLowerCase(Locale.ENGLISH); }

Target:
private String getDbVendor() { return dbClient.getDatabase().getDialect().getId(); }
Source:
private ScriptExecutorFactory() { }

Target:
private ScriptExecutorFactory() { super(); }
Source:
public JsonRpcResult getMatchedStylesForNode(JsonRpcPeer peer, JSONObject params) { final GetMatchedStylesForNodeRequest request = mObjectMapper.convertValue( params, GetMatchedStylesForNodeRequest.class); final ArrayListAccumulator<StyleInfo> styles = new ArrayListAccumulator<StyleInfo>() { @Override public void store(StyleInfo object) { if (!object.isDefault()) { super.store(object); } } }; mDocument.postAndWait(new Runnable() { @Override public void run() { mDocument.getElementStyle(request.nodeId, styles); } }); return new GetMatchedStylesForNodeResult(styles); }

Target:
public JsonRpcResult getMatchedStylesForNode(JsonRpcPeer peer, JSONObject params) { final GetMatchedStylesForNodeRequest request = mObjectMapper.convertValue( params, GetMatchedStylesForNodeRequest.class); final GetMatchedStylesForNodeResult result = new GetMatchedStylesForNodeResult(); final RuleMatch match = new RuleMatch(); result.matchedCSSRules = ListUtil.newImmutableList(match); match.matchingSelectors = ListUtil.newImmutableList(0); Selector selector = new Selector(); selector.value = "<this_element>"; CSSRule rule = new CSSRule(); rule.origin = Origin.REGULAR; rule.selectorList = new SelectorList(); rule.selectorList.selectors = ListUtil.newImmutableList(selector); rule.style = new CSSStyle(); rule.style.cssProperties = new ArrayList<>(); match.rule = rule; rule.style.shorthandEntries = Collections.emptyList(); mDocument.postAndWait(new Runnable() { @Override public void run() { Object elementForNodeId = mDocument.getElementForNodeId(request.nodeId); if (elementForNodeId == null) { LogUtil.w("Failed to get style of an element that does not exist, nodeid=" + request.nodeId); return; } mDocument.getElementStyles( elementForNodeId, new StyleAccumulator() { @Override public void store(String name, String value, boolean isDefault) { if (!isDefault) { CSSProperty property = new CSSProperty(); property.name = name; property.value = value; match.rule.style.cssProperties.add(property); } } }); } }); result.inherited = Collections.emptyList(); result.pseudoElements = Collections.emptyList(); return result; }
Source:
public List<String> showAllLocks() { List<String> returnValue; log.warn("All in memory locks will be shown"); globalLock.lock(); try { returnValue = new ArrayList<String>(); for(Map.Entry<String, InternalLockView> entry : locks.entrySet()) { String lock = new StringBuilder("The object id is : ").append(entry.getKey()).append(' ').append(entry.getValue()).toString(); returnValue.add(lock); log.warn(lock); } } finally { globalLock.unlock(); } log.warn("All in memory locks were shown"); return returnValue; }

Target:
public List<String> showAllLocks() { List<String> returnValue; log.warn("All in memory locks will be shown"); globalLock.lock(); try { returnValue = new ArrayList<String>(); for(Map.Entry<String, InternalLockView> entry : locks.entrySet()) { String lock = new StringBuilder("The object id is : ").append(entry.getKey()).append(' ').append(entry.getValue()).toString(); returnValue.add(lock); } } finally { globalLock.unlock(); } log.warn("All in memory locks were shown"); return returnValue; }
Source:
public void setObject(int index, Object value, int sqlType) throws SQLException { if (value == null) statement.setNull(index, sqlType); else statement.setObject(index, value); }

Target:
public void setObject(int index, Object value, int sqlType) throws SQLException { if (value == null) { statement.setNull(index, sqlType); } else { statement.setObject(index, value); } }
Source:
private void stopListening() { if (dependencies != null) { for (int i = 0; i < dependencies.length; i++) { IObservable observable = dependencies[i]; observable.removeChangeListener(privateInterface); } } }

Target:
private void stopListening() { if (dependencies != null) { for (IObservable observable : dependencies) { observable.removeChangeListener(privateInterface); } } }
Source:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_firestore_paging, menu); return super.onCreateOptionsMenu(menu); }

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_firestore_paging, menu); return true; }
Source:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { } return "<unknown:" + oid + ">"; }

Target:
public static String toString(int oid) { try { Field[] fields = Oid.class.getFields(); for (Field field : fields) { if (field.getInt(null) == oid) { return field.getName(); } } } catch (IllegalAccessException e) { } return "<unknown:" + oid + ">"; }